in reply to grep exact words

When using grep(), you are iterating over each item in the list (in this case @serv). An alias to the item is made on each pass, which is stored in $_ for you. Your example does a simple pattern match against $ARGV, so let's just change that to do an equality test:

#!perl -w use strict; my @serv = qw(foo bar baz); for my $arg (@ARGV) { # exact match (foo/foo match, but not foo/Foo) my $valid_arg = grep { $arg eq $_ } @serv; # case insensitive (foo/foo match, so do foo/Foo) # my $valid_arg = grep { lc($arg) eq $_ } @serv; die("Invalid argument '$arg'.\n") unless ($valid_arg); }

Replies are listed 'Best First'.
Re^2: grep exact words
by Anonymous Monk on Jun 26, 2004 at 00:11 UTC

    This is the code I have used and its not working....am I missing some syntax here?

    open (FILE, "<$list") or die "$list failed: $!\n"; @srvr = <FILE>; close (FILE); foreach $ARGV ( @ARGV ) { #$exists = grep { $ARGV eq $_ } @srvr; if (!$exists) { print "Cant do this"; # exit (1); } }

    20040626 Edit by Corion: Added CODE tags

      You've probably still got line endings ("\n") on the values in @srvr. See perldoc -f chomp.

      Do you know you have the exists line commented out?

      We're not really tightening our belts, it just feels that way because we're getting fatter.
      open (FILE, "<$list") or die "$list failed: $!\n"; chomp(@srvr = <FILE>); #note close (FILE); foreach $ARGV ( @ARGV ) { print "Comparing <$ARGV> to\n"; $exists = grep { print " <$_>\n"; $ARGV eq $_ } @srvr; if (!$exists) { print "Cant do this"; # exit (1); } }

      We're not really tightening our belts, it just feels that way because we're getting fatter.
Re^2: grep exact words
by Anonymous Monk on Jun 26, 2004 at 00:08 UTC
    Hello , For some reason the code isnt working.... Actually I am reading the @serv from a text file and comparing the ARGV to the values in the text file. I dunno where the error is coming up.