Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1007948]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2018-02-19 02:41 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (258 votes). Check out past polls.