Documenting Problems That Were Difficult To Find The Answer To

The Perl For Variable Modification Gotcha

What does this code do?

#!/usr/bin/perl -w

use strict;

my @arr = ( 1, 2, 3, 4, 5, 6, 7, 8, 9 );

for my $val ( @arr ) {

The answer? It increments every value inside @arr!

Not what I expected – as I assumed that by assigning the value into a specified variable (especially one declared with my) all that would happen would be that the local variable $val gets incremented and have no side-effects on the array @arr.

This is a quirk of Perl whereby the variable is actually masquerading as the actual element within the array. You can try this code for yourself!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: