Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: You can't assign $_ to a hash in a foreach statement

by ikegami (Patriarch)
on Apr 08, 2022 at 16:49 UTC ( [id://11142846]=note: print w/replies, xml ) Need Help??


in reply to You can't assign $_ to a hash in a foreach statement

No.

For starters, a foreach loop never assigns to the variable. It makes it an alias to the value for that iteration.

And even if it did assign, the original value is restored at the end of the loop, so it would be of no use to you.

$_ = "abc"; say; for (qw( def ghi )) { say; } say;

Output:

abc def ghi abc

Replies are listed 'Best First'.
Re^2: You can't assign $_ to a hash in a foreach statement
by markdibley (Sexton) on Apr 08, 2022 at 17:03 UTC

    You are right about the scope and actually for my purposes it is not necessary. I shouldn't have included the die at the end as it's output and the modified hash structure is not required. Sorry.

    perldoc says "The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn." So I was expecting to be able to use a hash reference as VAR. It doesn't mention aliasing. But as you say, the answer does appear to be No.

      perldoc says "The foreach loop iterates over a normal list value and sets the scalar variable VAR

      $var->{$y} isn't a variable.


      the modified hash structure is not required

      Did you just say it's not necessary to change $var->{$y}? Then why do you do it?


      t doesn't mention aliasing.

      Maybe, but it does mention the variable acts as an alias.

      If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-16 17:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found