Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Auto-incrementing strings in for loops

by JadeNB (Chaplain)
on Nov 20, 2009 at 03:59 UTC ( [id://808331]=perlquestion: print w/replies, xml ) Need Help??

JadeNB has asked for the wisdom of the Perl Monks concerning the following question:

It seems to me that the first and second code paragraphs below should behave identically, and the third should behave nearly identically (except that it increments only once). As shown, the behaviour is quite different (on Perl 5.10.1 and, with the obvious modification, Perl 5.8.9). Am I missing something obvious?

$_ = 'a'; $_++ and say; # => 'b' $_++ and say; # => 'c' $_ = 'a'; $_++ and say for 1..2; # => '2', '3' $_ = 'a'; $_++ and say for 1; # => Modification of a read-only value attempted

UPDATE: Oops, for aliases $_, so I'm not aliasing incrementing the $_ that I think I'm aliasing incrementing. Sigh, sorry ….

Replies are listed 'Best First'.
Re: Auto-incrementing strings in for loops
by colwellj (Monk) on Nov 20, 2009 at 04:12 UTC
    Jade,
    it seems to me that for part 2 you are 'say'ing the for loop and thus $_ will be the constant 1 then 2.
    For part three perhaps perl is compiling 'for 1' to be just '1 ' and thus you are attempting to $_++ a constant ('1')?
      No. The for has the lowest of priorities.
      $_++ and say for 1..2;
      is not equivalent to
      $_++ and ( say for 1..2 );

      That's not even legal. The original statement is indeed equivalent to

      ( $_++ and say ) for 1..2;
      it seems to me that for part 2 you are 'say'ing the for loop and thus $_ will be the constant 1 then 2.
      Thanks for your thoughts, but the parsing you suggest is not quite right:
      $ perl5.10 -MO=Deparse,-p -E 'say for 1..2' BEGIN { $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } ; say($_) foreach (1 .. 2); -e syntax OK
      That is, say for ... is understood as say($_) for .... The problem is, unfortunately, much sillier than that: for aliases $_, so I wasn't incrementing the variable that I thought I was incrementing!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-03-28 18:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found