Search code examples
perloperatorsoperator-precedence

Perl: what's the meaning of .=~


In a perl script, I occasionally wrote

my $s = "text";
$s .=~ " another text";
print "$s\n";

The expected result text another text was not printed, instead weird text as textߞ������ߋ��� was shown in my terminal.

No doubt: the error was the operator .=~ while indeed, I wanted to write .=

But I'm curious: Why isn't .=~ a syntax error? What's the meaning of this operation?


Solution

  • When choroba isn't around ;) you can use B::Deparse and ppi_dumper to tell you what you're dealing with ( .= and ~ )

    $ perl -MO=Deparse,-p -e " $foo .=~ /bar/; "
    ($foo .= (~/bar/));
    -e syntax OK
    
    
    $ ppi_dumper foo.pl
    PPI::Document
      PPI::Statement
        PPI::Token::Symbol          '$foo'
        PPI::Token::Whitespace      ' '
        PPI::Token::Operator        '.='
        PPI::Token::Operator        '~'
        PPI::Token::Whitespace      ' '
        PPI::Token::Regexp::Match   '/bar/'
        PPI::Token::Structure       ';'