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

Re: Remove letters from variables used in math operation?

by graff (Chancellor)
on Dec 09, 2012 at 03:31 UTC ( #1007948=note: print w/ replies, xml ) Need Help??


in reply to Remove letters from variables used in math operation?

If I were expecting extraneous, insignificant letters at the ends of digit strings, and wanted to treat the digits as integers to be summed, ignoring the letters, I'd do it like this:

while (my $line = <DATA>) { chomp $line; my @fields = split /,/, $line; my @ints = grep /^\d+$/, map { s/^(\d+)[a-z]?$/$1/; $_ } @fields; my $sum = 0; $sum += $_ for ( @ints ); print $sum, "\n"; warn "found non-integer fields at line $.: $line\n" if ( @fields ! += @ints ); } __DATA__ 86f,934e,92,102i,14,19,222,
The point is, adapting to variable input, and being "permissive" about what counts as usable input, is all well and good, but any variability - any need of flexibility - implies a risk that there might be more variation than expected. (That's just my view based on experience; if you happen to be fully confident about the nature of your input, you can skip this degree of caution.)

Still, if the input might contain things that, based on the OP description, really shouldn't happen (e.g. "23e45" or "10/15" or "-0.9%" or ...), it seems worthwhile to get warnings about that. Even if those things don't ever show up, there's no harm done (beyond using some extra cpu cycles).

And frankly, given the samples shown in the OP, I'd have to ask, just for the sake of being careful: Are you really quite sure that none of those letters were meant to be part of hexadecimal numerics?


Comment on Re: Remove letters from variables used in math operation?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2014-12-27 06:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls