Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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.

<radiant.matrix>
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


Comment on Re: When does '123' become the number 123.0?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (16)
As of 2014-10-23 14:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (125 votes), past polls