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

Hello Monks, this question is probably rudimentary but I can not seem to figure it out on my own. I have a file and in it is a bunch of paths like this: "\\my.domain.net\Apps\Sketchup" "\\fs-10\licenses\Sketchups" and so fourth - there are alot of lines in this file. I am trying to write a script that takes standard in like ./script.pl "Apps\Sketchup" and then matches the line in the file and sets the first column to one variable and the second colums to another variable sans the quotes. But I am stuck on the matching at this point. Here is my script so far:
$my_default="\\\\my\.domain\.net\\"; $my_file="info.txt"; my $path = shift @ARGV; sub usage{ print STDERR "\nUsage:\n"; print STDERR "\t$0 \"the\path\"\n"; print "\n"; } sub grep_pattern{ # print "$patten\n"; foreach (@my_data) {print "$_\n" if /$pattern/; } print "\n\n"; } sub print_array{ for ($i=0; $i<=$#my_data;$i++) {print $my_data[$i], "\n"; } print "\n\n"; } unless ($path){ &usage; exit (-1); } open(HANDLE, $my_file) || die("Open the file failed!"); @my_data=<HANDLE>; print_array; # Try and find the ARGV $pattern = $path; print "Searching for: $pattern\n"; grep_pattern;
At this point I cant even get a match. Can one of you Monks point me in the right direction. Thanks in advance

Replies are listed 'Best First'.
Re: Pattern matching and setting the match to a variable
by kyle (Abbot) on Feb 15, 2008 at 22:10 UTC

    Things like \S in your "pattern" are being interpreted as regular expressions. You should quotemeta before using the string as a pattern. This is also the same as doing /\Q$pattern/ for a pattern.

    If you're just matching literal strings, though, index would be a good way to go.

      THat worked perfectly!
      {print "$_\n" if /\Q$pattern/;
      Thanks to all who replied.
Re: Pattern matching and setting the match to a variable
by starX (Chaplain) on Feb 15, 2008 at 22:09 UTC
    Try checking regular expression return values. Given this:
    my $line = "I am the very model of a modern major general."; my $good_match = $line =~ m/major/; my $bad_match = $line =~ m/corporal/; print "$line\n" if $good_match == 1; # Prints the line. print "$line\n" if $bad_match == 1; # Doesn't print anything.
    A successful regular expression match will return 1, so you can check against that. It prints the line if the match was made, and doesn't if it wasn't.

    Update: Whoops, missed that you were doing that implicitly. Kyle has the correct answer.

Re: Pattern matching and setting the match to a variable
by ikegami (Patriarch) on Feb 16, 2008 at 19:53 UTC
    for (my $i=0; $i<=$#my_data;$i++)
    isn't as clear as (and no more efficient than)
    for my $i (0 .. $#my_data)
    And more specifically,
    for ($i=0; $i<=$#my_data;$i++) {print $my_data[$i], "\n"; }
    can simply be written as
    for (@my_data) {print $_, "\n"; }