Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Dereference string in foreach

by choroba (Abbot)
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.
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: Dereference string in foreach
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (11)
As of 2014-07-24 17:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (163 votes), past polls