Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
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.


Comment on Re: ref to read-only alias ... why?
Select or Download Code
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?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2014-09-20 01:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls