Friday, January 13, 2006

A Perl Gotcha

I've been using perl for about 6 years now. I don't claim to be an expert as I tend to be working on things by myself and thus don't learn from others. Plus it tends to be text manipulation in a small script, so less need for all the wonderous things that perl can do.

Anyway, a short while ago I had a problem and eventually when I figured out what was going on I was amazed that I didn't already know it, and that I hadn't already come across it.

foreach my $tmp (@my_array) {
$tmp =~ s/(\w+)\.(\w+)/$1/;
# do somthing with $tmp;
}

I never knew that $tmp is an actual pointer into the array, and thus I am modifying the array entry with the regular expression, not just the tmp variable.

instead, use a variable to index the array, or use $_

foreach my $i (0 .. $#my_array) {
my $tmp = $my_array[$i];
#etc.
}

foreach (@my_array) {
my $tmp = $_;
#etc
}

Well there are a million ways of doing it. Probably better than those too.

0 Comments:

Post a Comment

<< Home