Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Floats and numeric context

by perlcgi (Hermit)
on May 14, 2000 at 19:57 UTC ( [id://11499]=perlquestion: print w/replies, xml ) Need Help??

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.

Replies are listed 'Best First'.
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"
      I don't think so - have you missed the s/\$//; in the second one-liner?
      perlcgi
        No, you're right takshaka. Thanks man.
        (removed in deference to proper timeflow)
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!
      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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-19 21:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found