in reply to Set::Scalar - Regexp as method parameter?

Does this already work [...] ?

Taking a peek at the source, apparently not, so you'd need to augment has with your own functionality, either be redefining it directly or via a subclass.

[...] and I'm doing something wrong to achieve my goal ?

Trying to pass a bare regex isn't going to work, as you'll end up passing it's return value against (in your example anyway) whatever $_ is before you even get to the sub.

Instead, you should use qr (my personal preference) or pass the string you want to use (ie, the regex minus the enclosing //'s) so that the regex gets evaluated when you really want it to: inside the function/method...

foo( qr/ba[rz]|quux/ ); foo( 'ba[rz]|quux' ); sub foo { my $regex = shift; # //'s not necessary if $regex # was built with qr. return grep /$regex/ => @foo; }
[...] How to alternatively implement that?

Depending on your needs, you might be able to use Quantum::Superpositions' any function...

any(@set) =~ /c\((.+)\)/;

... although I note I couldn't get it working with Q::S's all, so be sure to test for yourself.

    --k.


Replies are listed 'Best First'.
Re: Re: Set::Scalar - Regexp as method parameter?
by Juerd (Abbot) on Apr 27, 2002 at 20:57 UTC

    //'s not necessary if $regex was built with qr.

    Actually, if you leave out the slashes, the regex is put in string context, and the speed gain is lost.

    $foo =~ '^string literal$'; # Does not equal /\Q^string literal$/ $foo =~ $string; $foo =~ subroutine(); $foo =~ bareword; # Unless $INC{'strict.pm'} $foo =~ $precompiled_regex; # Is stringified first! $foo =~ /$precompiled_regex/; # Faster
    I've even seen people do bizarre things because they think qr//s are faster without slashes:
    # Bad: (well, it works, but not the way you want it to) $foo =~ $qr; $foo =~ s//bar/; # Good: $foo =~ s/$qr/bar/;

    - Yes, I reinvent wheels.
    - Spam: Visit eurotraQ.