Operator "= ~" and "! ~" Makes an odd hash counter in Perl when passed in a subroutine

I am making a subroutine that takes an array of hashes that have the same keys with different values. As a requirement, there are values ​​that have conditional operations.

Example:

use strict;
use warnings;
use Data::Dumper;

sub test {
  my @data = @_;
  print Dumper(@data);
}

test(
  {
    'value' => 1 == 2
  },
  {
    'value2' => 4 == 4
  }
);

      

output:

$VAR1 = {
          'value' => ''
        };
$VAR2 = {
          'value2' => 1
        };

      

but when I use the =~

or operators !~

, the interpreter throws this error:

Odd number of elements in anonymous hash at ...

test(
  {
    'value' => 1 == 2
  },
  {
    'value2' => 'a' =~ /b/
  }
);

      

output:

$VAR1 = {
          'value' => ''
        };
$VAR2 = {
          'value2' => undef
        };

      

It seems that for false assertions, the hash value returns undef

not ''

. I've also tried putting undef directly on the hash value and it works fine.

Question:

  • Why is perl outputting this behavior?
  • What's the best solution for this?
+3


source to share


1 answer


The match operator in the context of a list returns an empty list on failure. you can use

scalar( 'a' =~ /b/ )

      



or

'a' =~ /b/ ? 1 : 0

      

+5


source







All Articles