Search code examples
perloperators

What does =~ mean in Perl?


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?


Solution

  • =~ 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/;