Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: When does '123' become the number 123.0?

by radiantmatrix (Parson)
on Jun 17, 2008 at 18:28 UTC ( #692564=note: print w/replies, xml ) Need Help??

in reply to When does '123' become the number 123.0?

I'm reading a comma-separated-value ascii text file containing numerical data, e.g. "123,234,456" on each line.

I'm using 'split' to separate the fields of each line

Don't do that. Use Text::CSV_XS. CSV files will bite you if you're not careful.

Is it the string "123" or the number 123.0? And does it make any difference to the perl programmer?

It's a scalar. Don't worry about how it's stored under the hood, it will be a string or an integer or a float when you need it to be one of those things.

Under the hood, since you're using split, you'll be getting strings. But:

my $line = '123,456,789'; my ($val) = split(',' , $line); # $val is the string '123' $val += 2; # $val is now the integer 125 $val /= 2; # $val is now the float 62.5 print "I ended up with $val" # $val is treated as the string '62.5 +'

The whole point of Perl's weak typing is that you don't have to worry about this sort of thing. If you want to validate that your scalar contains a certain type of data (not under the hood, mind you), check out Data::Validate.

Ramblings and references
“A positive attitude may not solve all your problems, but it will annoy enough people to make it worth the effort.” Herm Albright
I haven't found a problem yet that can't be solved by a well-placed trebuchet

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://692564]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2021-04-17 09:09 GMT
Find Nodes?
    Voting Booth?

    No recent polls found