15

Possible Duplicate:
What does =~ do in Perl?

In a Perl program I am examining (namly plutil.pl), I see a lot of =~ on the XML parser portion. For example, here is UnfixXMLString (lines 159 to 167 on 1.7):

sub UnfixXMLString {
    my ($s) = @_;

    $s =~ s/&lt;/</g;
    $s =~ s/&gt;/>/g;
    $s =~ s/&amp;/&/g;

    return $s;
}

From what I can tell, it's taking a string, modifying it with the =~ operator, then returning that modified string, but what exactly is it doing?

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74

2 Answers2

25

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern:

if ($string =~ m/pattern/) {

Or to extract components from a string:

my ($first, $rest) = $string =~ m{^(\w+):(.*)$};

Or to apply a substitution:

$string =~ s/foo/bar/;
  • 6
    More specifically, it’s used to bind a `m//`, `s///`, or `y///` (`tr///`) operator to a scalar. Regexes are not involved for the last one. It can also be used as `$var =~ $re`, which is pretty much the same as `$var =~ /$re/`. – tchrist May 02 '12 at 01:12
5

=~ is the Perl binding operator and can be used to determine if a regular expression match occurred (true or false)

$sentence = "The river flows slowly.";
if ($sentence =~ /river/)
{
    print "Matched river.\n";
}
else
{
    print "Did not match river.\n";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131