in reply to On patterns and more

I am sure the answers to your questions are in more or less every Perl related FAQ. $_ will be documented in perlvar, =~ will be in perlop, but this is a quiet Sunday evening, and I enjoy helping out Novice monks.

I think $_ has been adequately explained by ELISHEVA, I especially liked her explanation of it as ...whatever Perl thinks you are most likely to want...

=~ is the operator that binds a perl scalar variable to a regular expression. If you are not using $_, This is usually how you tell perl what variable you want to test against the regular expression. Consider ELISHEVA's second example:

while (<STDIN>) { chomp # same as chomp $_ if (/^#/) {....} # same as if ($_ =~ /^#/) { ....} }

With explicit variables this could be written:

while (my $line = <STDIN>) { chomp $line; # same as chomp $_ if ( $line =~ m/^#/ ) { # Action on $line. } }

In this form we have made the code a good deal clearer, and easier to understand by a novice, But because we are no longer using the $_ default variable we need to tell perl what variable the regular expression should be matched with. The whole $variable =~ m/regexp/ returns true if the variable matches regular expression, or false otherwise, so within an if statement it allows you to select only lines that match.

The other use for the =~ operator is for substitutions. If you write:

$line =~ s/^#/# Comment /;

Then you substitute everything that matches on the left with the string on the right. In this case any lines in the input that start with hash will have 'Comment' prepended.