Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Update: problem with scalar

by graff (Chancellor)
on Apr 24, 2016 at 19:33 UTC ( [id://1161392]=note: print w/replies, xml ) Need Help??


in reply to Update: problem with scalar

If I want to read array elements from lines of input, and I intend to treat each element as a numeric value, I'd load the array from the file like this (assuming that the input is coming from STDIN or from any file(s) named on the command line when I run the script):
use Scalar::Util 'looks_like_number'; my @array; while (<>) { chomp; if ( looks_like_number( $_ )) { push @array, $_; } else { # skip this part if you don't care to know about bad input +... warn "Unusable input line skipped: $_\n"; } }
It doesn't matter to me what the input looks like or where it comes from. When I expect it to be of a certain type, I test to see that it really is that type before I actually use it (i.e. I seldom treat data files or STDIN as "trusted" sources).

UPDATE: Having played with that snippet a bit, I'm happy to notice that leading and trailing whitespace characters do not affect the results of "looks_like_number()" (i.e. it returns true for " 123 ", "\t-456\n", and so on). The same is true for arithmetic operators: you can add, subtract, multiply and divide numeric strings that have leading and trailing whitespace.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-25 14:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found