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.


In reply to Re: On patterns and more by chrestomanci
in thread On patterns and more by Sary

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.