I am writing a script in Perl and have a question about Perl's foreach
construct.
It appears that if you change one of the loop variables it changes in the actual array. Is this in fact the case, or have I done something completely wrong?
I want to change a string like abc.abc#a
to abc_abc_a
(underscores for non alpha-numeric characters), but I need to preserve the original value in the array for later use.
I have code that looks something like this:
@strings = ('abc.abc#a', 'def.g.h#i');
foreach my $str (@strings){
$str =~ s/[^0-9A-Za-z]/_/g;
print $str, "\n"; #Actually I use the string to manipulate files.
}
I could solve the problem by doing the following:
@strings = ('abc.abc#a', 'def.g.h#i');
foreach my $str (@strings){
my $temp = $str; #copy to a temporary value
$temp =~ s/[^0-9A-Za-z]/_/g;
print $temp, "\n"; #$str remains untouched...
}
but is there a more efficient way to accomplish this?
Thank you very much!