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

It's been a while since I've sat down and written any Perl (as will become obvious).

I'm using a regexp to parse thru a file that contains output from a grep. The grep was on the pattern "*.pl" -- I went and greped for all html files that are calling perl scripts on my site.

I'm trying to do a pattern match for "pl", and print the match, which hopefully will give me a nice list of all the perl scripts with no extraneous html.

Here's the code that doesn't get a match for anything (right now I'm just printing to stdout until I figure out why the regexp isn't matching):

#!/usr/bin/perl open FILE, "grepfile" or die "where is grepfile?"; while ( $blah = <FILE> ) { $blah =~ /pl/; if ($1) { print $1 } else { print "no match" } } print $1; close FILE; exit;

Replies are listed 'Best First'.
Re: pattern matching -- feeling stoopit
by Caillte (Friar) on Oct 02, 2001 at 20:36 UTC

    This looks like homework but....

    m/(pl)/ will store a value in $1, m/pl/ won't. It's the brackets that define what gets written to $n

    $japh->{'Caillte'} = $me;

      $doh == true; It ain't homework--I wish I was taking a refresher course though. Much thanks!
Re: pattern matching -- feeling stoopit
by arturo (Vicar) on Oct 02, 2001 at 20:50 UTC

    What's in grepfile ? The output of your grep ? (which is what, exactly? filename: [ matching line ] ? -- I'll assume that)

    You need to put capturing parens in the regex for $1 to get set by a successful match. Now, assuming valid filename characters are \w (not quite true, but probably OK in the present context) what you want to match is not just the "pl" but the "." that comes before it and a bunch of word characters before that. And you probably only want the ones that are referenced within form action tags, for that matter, but let's leave that for a future refinement. So the regex you want matches "one or more word ( \w ) characters, followed by a literal ., followed by 'pl'." => /\w+\.pl/ (\w character => one or more => a literal dot => "pl" ).

    Toss in the parentheses, and make the match case-insensitive (maybe necessary, maybe not), and use some nifty shorthand to put the results of $1 into a variable, and you get:

    while ( my $blah = <FILE> ) { if (my ($filename) = ($blah =~/(\w+\.pl)/i) ) { print "$filename was found.\n"; } else { print "no match.\n"; } }

    HTH

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'