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

Re: ref to read-only alias ... why?

by tobyink (Abbot)
on Jan 05, 2012 at 22:47 UTC ( #946489=note: print w/replies, xml ) Need Help??


in reply to ref to read-only alias ... why?

From perlsyn's section on foreach loops:

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.

What that's saying is that given:

use 5.010; use Data::Dumper; my $foo = "world"; my $bar = "Hello planet"; my $iter = 0; foreach my $x ((1, $foo, substr($bar,6))) { local $@ = undef; printf "Iteration %d:\n", ++$iter; eval { $x = "World" } or say $@; } print Dumper [$foo, $bar];

The first iteration will fail as it's essentially trying to assign 1 = "Hello"; the other iterations will succeed because $foo and substr($bar,6) are both lvalues, so can be assigned to.

In your case, $_ is an alias for the constant 1, not an lvalue, so can't be assigned to.

Replies are listed 'Best First'.
Re^2: ref to read-only alias ... why?
by Eliya (Vicar) on Jan 05, 2012 at 23:28 UTC
    In your case, $_ is an alias for the constant 1, not an lvalue, so can't be assigned to.

    This doesn't really answer the OP's question why it does not fail when you try to modify the constant via a reference to the alias.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://946489]
help
Chatterbox?
[Corion]: But I don't expect more than 100 to be active at the same time, so I'm not really sure if there is a not-too-fancy data structure that is maintained with few lines of code where the performance is better than the linear scan ;)
[Corion]: But I should do a mock-up program so that others can see what I'm talking about ;)
[robby_dobby]: Corion: I hope you know all too well that passing around "fancy" datastructures is a recipe for disaster :-)
[robby_dobby]: As in, it's-too-fancy- that-it-will-be- messy-to-handle
[choroba]: bit vectors as keys?
[robby_dobby]: Hmm, I keep falling asleep at my desk, while maintaining an active appearance. Am I getting old?
[robby_dobby]: Every time I fall asleep, there's a small guy in the dreams, shouting "Whoo!" and it jolts me awake. :/
[Lady_Aleena]: robby_dobby, at least you aren't driving. I seem to always be driving somewhere in my dreams and end up at a weird house.

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2017-05-29 08:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?