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

Bring forth the holy hand grenade! I am about ready to blow up. I have an output tree from Parse::RecursiveDescent, and i now need to match the results from the rule: name ($name), to another name from another input file ($inputFileName). Something like, while ($name = $inputFileName){ print $name; } So in effect i want to use $name (the output of the rule in the tree) to search, the input file for occurences of itself. i.e if $name = bob, i want to find all occurences of bob in the input file. thx from a choirboy

Replies are listed 'Best First'.
Re: searching using a scalar as pattern
by Masem (Monsignor) on Jan 18, 2002 at 21:07 UTC
    Basically, once you have your $name, you want to see where it appears in a second file. This step is equivalent to using the unix 'grep' to search through a file, and if you have that installed, you could simply use a system command to get the results. But a more portable solution would be to load in the text file, and use perl's built-in grep to find your string:
    open FILE, "<$inputFileName" or die "Cannot open: $!"; my @lines = <FILE>; my @matched_lines = grep { /$name/ } @lines; close FILE;

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

Re: searching using a scalar as pattern
by strat (Canon) on Jan 18, 2002 at 22:00 UTC
    To be safe of certain chars in $name, I'd rather use something like:
    my @matched_lines = grep { /\Q$name/ } @lines;
    Otherwise, if there is a / in $name, a syntax error might appear...

    Best regards,
    perl -e "print a|r,p|d=>b|p=>chr 3**2 .7=>t and t"

Re: searching using a scalar as pattern
by PrimeLord (Pilgrim) on Jan 18, 2002 at 22:03 UTC
    Someone correct me if I am wrong, but wouldn't it be better to just read the file in a line at a time?
    my @matched_line; open FILE, "<$inputFileName" or die "$!\n"; while (<FILE>) { push @matched_line, $_ if (/$name/); } close FILE;
    I am relativley new to Perl so that may not work, but I thought I would throw it out there.