perlcgi has asked for the wisdom of the Perl Monks concerning the following question:
I seek the wisdom of the Perlmonks concerning numeric context and floating point numbers. Specifically the following works as intended, i.e. $_ is interpreted in numeric context:
perl -e "@stuff=(5,5,5);my $x=0;foreach (@stuff) {$x+=$_};print $x"
But not with floats:
perl -e "@stuff=($0.5,$0.5,$0.5);my $x=0;foreach (@stuff){s/\$//; $x+=$_}; print $x"
So, O wise-ones, what transformation/incantation/prayer is required to get $_ interpreted in numeric context.
God be with you.
Re: Floats and numeric context
by takshaka (Friar) on May 14, 2000 at 20:27 UTC
|
@stuff=($0.5,$0.5,$0.5)
You're concatenating the value of the special variable $0
with 5. For the example you gave, this would fill @stuff
with ('-e5', '-e5', '-e5').
Watch out for variable interpolation.
perl -e "@stuff=('$0.5', '$0.5', '$0.5');my $x=0;foreach (@stuff){s/\$//; $x+=$_}; print $x"
or
perl -e "@stuff=qw($0.5 $0.5 $0.5);my $x=0;foreach (@stuff){s/\$//; $x+=$_}; print $x"
| [reply] [d/l] [select] |
|
I don't think so - have you missed the s/\$//; in the second one-liner? perlcgi
| [reply] |
|
No, you're right takshaka. Thanks man.
| [reply] |
|
(removed in deference to proper timeflow)
| [reply] |
RE: Floats and numeric context
by BBQ (Curate) on May 15, 2000 at 04:50 UTC
|
Not that it matters much, but your last ; was enclosing your foreach statement and not the $x+=$_ as I would suppose you wanted. I think one liners are cool, but you really gotta double check, cause its easy to misplace a comma, period or a bracket.
#!/home/bbq/bin/perl
# Trust no1!
| [reply] |
|
You can leave the semicolon off of the last statement in a block. The semicolon after the block is necessary to terminate the foreach statement.
| [reply] |
|