Perl's binding operator. (Perl got this from csh.)

=~ is used to specify the scalar variable that is being regexped or otherwise mangled by the expressions m//, s/// or tr///.

Same in simpler terms: The following...

if(/pattern/) {          # Pattern match
  # ...

s/something/other/gi;    # Pattern replace

tr/abc/def/;             # Character transliteration

...all operate on the scalar variable $_ - the default variable of many commands.

But with this operator, we can check other variables just as easily:

if($var =~ /pattern/) {

$var =~ s/something/other/gi;

$var =~ tr/abc/def/;

Now these operators match or modify the variable $var instead.

Return value is typically success/failure status in scalar context (so you can just use if($var =~ /pattern/)... to check if string $var matches the regular expression pattern.)

In list context the return value depends on operation done, but practically, the idea is same. If /g modifier is used, m// returns matched subexpressions ($1, $2, $3...) or, in case there's no parenthesis in the pattern, just list (1) if success. It returns empty list if there's no match. If /g is used, it likewise returns substrings or, if there's no parentheses in the pattern, whole matched strings. (I have been told s/// returns the same in list context. Must check later what tr/// returns...)

There's a related operator, !~, that has negated return value. (In other words, if($var !~ /pattern/)... checks if the pattern doesn't match.)

(Source: perlop)

In Perl 6, =~ is the smart match operator. It does more than the Perl 5 version, which just binds something to a s///, m//, or tr//. It compares its two operands in a way that is most likely to be useful. when compares $_ to its argument using =~ to determine the condition.

=~ Operates according to the following table:

  $a    |    $b    |   $a =~ $b
 expr   |  list    | if $a =~ any($b)
 list   |  list*   | if any($a) =~ any($b)
 hash   |  sub(%)  | if $b(%$a)
 array  |  sub(@)  | if $b(@$a)
 expr   |  sub($)  | if $b($a)
 expr   |  sub()*  | if $b()
 hash   |  hash    | if grep {exists $a{$_}} %$b
 hash   |  array   | if grep {$a{$_}} @$b
 hash   |  regex   | if grep {/<$b>/} keys %$a
 hash   |  scalar  | if $a{$b}
 array  |  array   | if any(@$a) =~ any(@$b)
 array  |  regex   | if grep {/<$b>/} @$a
 array  |  number  | if $a$b
 array  |  expr    | if any(@$a) =~ $b
 object |  class   | if $a.isa $b
 object |  method  | if $a.$b()
 expr   |  regex   | if $a matches /<$b>/
 expr   |  number  | if $a == $b
 expr   |  string  | if $a eq $b
 expr   |  boolean*| if $b
 expr   |  undef   | unless defined $a

If these types cannot be determined at compile time, they are run time matched instead. Except in the cases marked with *, =~ commutes. any and all are superpositions.

Log in or register to write something here or to contact authors.