Thursday, May 1, 2008

Perl: The $_ special variable

We could use a conditional as
if ($sentence =~ /under/)
{
print "We're talking about rugby\n";
}
which would print out a message if we had either of the following
$sentence = "Up and under";
$sentence = "Best winkles in Sunderland";

But it's often much easier if we assign the sentence to the special variable $_ which is of course a scalar. If we do this then we can avoid using the match and non-match operators and the above can be written simply as
if (/under/)
{
print "We're talking about rugby\n";
}

The $_ variable is the default for many Perl operations and tends to be used very heavily.

No comments:

Post a Comment