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

Re: Counting variable initialization

by tlm (Prior)
on Mar 29, 2005 at 18:25 UTC ( [id://443222]=note: print w/replies, xml ) Need Help??


in reply to Counting variable initialization

Try -MO=Deparse to see what perl thinks of your code:

$ perl -MO=Deparse 443218.pl my(@l) = ('10', '20', '30'); foreach $_ (@l) { my $t += $_; } print $t; 443218.pl syntax OK
where file 443218.pl contains
$ cat 443218.pl use warnings; use strict; my @l = qw/10 20 30/; my $t += $_ foreach @l; #my $t; #$t += $_ foreach @l; print $t;

the lowliest monk

Update: Added the contents of the file given to -MO=Deparse for clarification.

Replies are listed 'Best First'.
Re^2: Counting variable initialization
by ikegami (Patriarch) on Mar 29, 2005 at 18:41 UTC

    Deparse is wrong in this case, on two counts: 1) print($t) is not strict safe in the deparsed version, but it is in the original, and 2) print($t) prints the package variable in the deparsed version, but not in the original.

    To answer the OP, my is considered a function for syntax purposes, so my ... foreach ...; means (my ...) foreach ...;, which makes no sense.

      I wondered about the fact that strict seemed to be violated. I defer to your interpretation, but it is a bummer to know that Deparse can be wrong, because I use it quite a bit. Sorry to the OP for the wrong info.

      the lowliest monk

Re^2: Counting variable initialization
by eric256 (Parson) on Mar 29, 2005 at 19:34 UTC

    Thats odd. That isn't the deparse I get at all. Before:

    use strict; my @l = qw/10 20 30/; my $i += $_ foreach @l; my $t; $t += $_ foreach @l; print '$t = ' . $t . "\n"; print '$i = ' . $i . "\n";
    After:
    use strict 'refs'; my(@l) = ('10', '20', '30'); ; my $i += $_ foreach (@l); my $t; ; $t += $_ foreach (@l); print '$t = ' . $t . "\n"; print '$i = ' . $i . "\n";
    Output for both scripts:
    $t = 60 $i =


    ___________
    Eric Hodges

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-16 16:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found