Checking has for a command line argument

I would like to search and print a match of the user entered $ARGV[0].
Im terrible with hashes and really dont know where to go from here.

The example data file

name location phone
Bugs holeintheground 5551212
Woody holeinthetree 6661313
Jerry holeinthewall 7771414

if the user enters "scriptname holeinthetree" at the command line, I want to return :

"Woody holeinthetree 6661313" or print an error message.

I got this far from an example in a book.

open ( IN, "peeplist" ) or die;
my @lines =<IN>;
#close (IN);
#
while ($line = <IN> ) {
  ($rtrname, $storename, $ip)=split(/ /,$line);
  $cstorename{$rtrname} = $storename;
  $cip{$rtrname} = $ip;
}
close (IN) ;

Thanks alot for the help !!

#!/bin/perl
$err=1;
open (IN,"peeplist") or die;
while (<IN>) {
  if (/\b$ARGV[0]\b/) {print; $err=0;}
}
close (IN);
if ($err==1) {print STDERR "not found\n"}
exit $err;

This uses perl's $_
With $line it becomes

...
while ($line = <IN>) {
  if ($line =~ /\b$ARGV[0]\b/) {print $line; $err=0;}
}
...

\b in regular expressions is a "word boundary".

1 Like

Thanks you very much MadeInG .. that worked.

I didnt have my notebook yesterday. I looked this up last night.

why doesnt

print grep /\Q$ARGV[0]\E/, @lines

work ?

Got that written down in my notes. Wouldnt have written it down if it didnt work at some point for me.

If you read the entire file into an array
you can print the array like that - without a loop.

@lines = <IN>;
print grep /\Q$ARGV[0]\E/, @lines;

Or even directly from the file

print grep /\Q$ARGV[0]\E/, <IN>;

But there is a small problem to detect the "not found" condition.

2 Likes

Ok yeah. Thanks again.