Home > Enterprise >  Why does `=~` behave differently than `eq` and `==` in list context?
Why does `=~` behave differently than `eq` and `==` in list context?

Time:03-13

Consider

my @array = ( 'x' =~ /y/, 'x' eq 'y', 1 == 2 );

and

my %hash = ( 'a', 'x' =~ /y/, 'b', 'x' eq 'y', 'c', 1 == 2 );

Using Data::Dumper, we see that =~ behaves differently than eq and ==

\@array = [
            '',
            ''
          ];
\%hash = {
           'a' => 'b',
           '' => undef
         };

Specifically it appears that the snippets of code above are being interpreted as

my @array = ( 'x' eq 'y', 1 == 2 );

and

my %hash = ( 'a', 'b', 'x' eq 'y', 'c', 1 == 2 );

Can someone provide an explanation for this arguably unexpected behavior?

CodePudding user response:

The match operation you use is not only about finding out if something has matched (scalar context) but also to give the match results (list context). To cite from the documentation:

Matching in list context
m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, that is, ($1, $2, $3...) (Note that here $1 etc. are also set). When there are no parentheses in the pattern, the return value is the list (1) for success. With or without parentheses, an empty list is returned upon failure

  • Related