Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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]
[ovedpo15]: another question about regex. if I have a string like this: "a/b/,c/d/e,5" I would like to remove the string after the last comma so the output will be "a/b/,c/d/e" how to do so?
[Corion]: ovedpo15: You could split on comma, and then join everything together, except the last part. Or you could match and make sure that the last part has no comma, like qr!,[^,]+$!, or you could use rindex.

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2018-05-27 10:32 GMT
Find Nodes?
    Voting Booth?