Skip to Content

Pronouns in Perl Syndicate content

Dave Sherohman's picture

Cross-posted from dream.in.code:

Quote:


That bit of code works beautifully. Thank you ever so much!

I do have a question regarding it. That default variable you use, $_, where was it defined? That is, how does it recognize the scalars within @stack, assign them to $_, and then print them? Seems like a really handy sort of tool, but I'm unclear as to why this works.

That's a big question which goes straight to the heart of Perl and plays a big role in why Perl is such a love-it-or-hate-it language.

Perl was created by a linguist (Larry Wall), not a computer scientist. Because of this, it incorporates a lot of things that appear in natural languages, but tend to be omitted from programming languages. One of those things is pronouns.

$_ is the primary pronoun of the Perl language. You can read "$_" as "that" to get a general sense of its purpose and meaning.

In practical terms, when you loop over a list, $_ is automatically aliased to the current value from the list if you haven't explicitly assigned that value to another variable:

for (1 .. 3) { print "$_ "; } # prints '1 2 3'

$_ = 5;
for my $x (1 .. 3) { print "$_ "; } # prints '5 5 5'

Note that $_ is an alias of the list value, not a copy. Changing $_ will also change the original value. This is usually what you want, but can surprise you if you don't expect it:

my @arr = qw( 1 2 3 );
for (@arr) { $_ *= 2 }
print join ' ', @arr; # prints '2 4 6'

Pronouns also go the other way. Many Perl commands will operate on $_ by default if you don't provide an argument to them. Probably the most common places to see $_ used implicitly are with the "print" command and regex matching:

for ('a' .. 'c') { print; } # prints 'abc'

$_ = '123 Main St.';
/(\d+)/;  # equivalent to $_ =~ m/(\d+)/
print $1; # prints '123'

Post new comment