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

I want to match a string exactly, consider:

my $C = shift ; my @others = grep ( !/$C/, @_ );
Now consider

$passtoC = 'Vanilla';
my @list = qw / Vanilla Vanilla_Orange_Sherbert Vanilla_Fudge_Swirl / ;
All items match vanilla and nothing is put into others.

My solution is:

my @others = grep ( !/^$C$/, @_ );
Which produces the desired result. I'm just wondering if there is a more direct way, or if there is any possible weirdness that might result from specifying both ^ and $ in the same regexp.
  • Comment on Using a Regexp to match a string exactly

Replies are listed 'Best First'.
Re: Using a Regexp to match a string exactly
by Ratazong (Monsignor) on Jan 27, 2010 at 07:46 UTC

    Hi!

    There is no weirdness in using ^and $ in the same regex. However in your case, a simple compare (using eq) would also work. With the side-effect of making your code better readable and possibly faster.

    HTH, Rata
Re: Using a Regexp to match a string exactly
by bart (Canon) on Jan 27, 2010 at 10:13 UTC
    In Perl, there's no restriction for use of grep to just regexes! So: just use eq (or its inverse: ne) already.
    my $C = shift ; my @others = grep $_ ne $C, @_;

    p.s. Unless there are more parameters following the grep call not intended for (this) grep, you may just as well drop the parens.

      Thanks, I was unaware that grep supported eq/ne!

        Not just eq/ne... but any expression that returns a true or false value — which implies: any expression in scalar context. (undef, "" and 0 are false, anything else is true.)

        The generic variable $_ holds the value of the current item from the list. Actually, it's even stronger than that: $_ is an alias to the current item, which means: same value (by reference; you could say: same variable); different name. If you modify $_ in that expression, the original value will have changed. Example:

        @original= (0 .. 5); @true = grep $_*=2, @original; local $" = ", "; # for nicely formatted output print "original: @original\n"; print "output: @true\n";
        Result:
        original: 0, 2, 4, 6, 8, 10 output: 2, 4, 6, 8, 10

        Each item in the original array has been doubled. Of those, only the nonzero (true) values have been come through the grep filter.

Re: Using a Regexp to match a string exactly
by Anonymous Monk on Jan 27, 2010 at 07:39 UTC
    if( "one" eq "two" ){ print "uh oh\n"; } else { print "perldoc perlop\n"; } __END__
    perldoc perlop