Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a piece of code in which it seems like the m operator does not work properly. I am new to Perl, so I assume I'm doing something I shouldn't be. What do you think?
This is the output:
'fudge' does not match 'fudge'
of this:
use strict; sub test_reg1 { return "fudge"; } sub test_reg2 { print "'",$_,(/&test_reg1/i ? "' matches '" : "' does not match '" +),&test_reg1,"'\n"; } $_ = "fudge"; &test_reg2("fudge");

Replies are listed 'Best First'.
Re: Strange behaviour of m and $_
by Fletch (Bishop) on Oct 17, 2006 at 22:20 UTC

    Subroutine invocations don't interpolate in double quoted strings (of which m// is a special kind). Either store the results from your function in a scalar and let that interpolate, or use something like /@{[ test_reg1() ]}/ instead.

    And an aside, don't use the leading ampersand on subroutine calls; it does things to how the sub is called and unless you specifically have a reason to (and know why you're doing it) you should just omit it.

      And an aside, don't use the leading ampersand on subroutine calls; it does things to how the sub is called
      Slight clarification: that only applies when no () follow the sub name.
        ...except
        $\=$/; sub print { CORE::print("[$_[0]]"); } print('foo'); # foo &print('bar'); # [bar]
Re: Strange behaviour of m and $_
by jeffa (Bishop) on Oct 17, 2006 at 22:17 UTC

    Don't use global variables:

    print( test_reg('fudge','fudge') ? "matches\n" : "no matches\n" ); sub test_reg { my $this = shift; my $that = shift; return $this =~ /$that/i; }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)