Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Dereference string in foreach

by choroba (Bishop)
on Feb 13, 2013 at 21:05 UTC ( #1018635=note: print w/replies, xml ) Need Help??

in reply to Dereference string in foreach

See Foreach Loops. If the variable is not declared with my, it is implicitly localized. For each iteration, the variable is aliased to the value you are looping over. Therefore, in the first case, the loop variable $string is a different one than the $string defined before the loop: Try
$sref = \$string; foreach $string ( @array_of_strings ) { print $sref, \$string, "\n"; }
In the second snippet, you are using $string1 which is not localized. Therefore, $ref really points to it, and since you assign the value from the loop variable to it, you can acces the value by the reference. Note, though, that this is only a copy of the original value, which means you cannot change the original @array_of_strings by changing $$ref or $string1, but only $string2.
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Dereference string in foreach
by 7stud (Deacon) on Feb 13, 2013 at 23:01 UTC

    Here is the effect when perl localizes a variable:

    #Whoops.  An Anonymous Monk already posted a good example.

    And because a for loop aliases each element in the array to the loop variable, changes to the loop variable change the elements of the array.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1018635]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2018-02-19 18:15 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (266 votes). Check out past polls.