in reply to Pattern matching against a variable

Just put $pattern in the match e.g
## remove regex-unfriendly newline chomp( my $pat = <STDIN> ); open(FILE, "filename") or die("ack: $!"); while(<FILE>) { print if /$pat/; }
That will get a line of user input, loop over FILE and print if a given line matches $pat. Because regexes are interpolated the $ of $pat isn't interpreted as the meta-character $, but is interpolated into the regex match. See. perlop and perlre for more information on regexes and their quoting behaviour.
HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Pattern matching against a variable
by bonoboy (Sexton) on Nov 04, 2003 at 11:19 UTC
    Ok, here's the *actual* code:
    open (LOGFILE, "/var/log/tac_acc.log"); while (<LOGFILE>) { print if /$username/; #if (/$username/) { #print "<br>",$_; # } }
    Apologies for leaving the comments in there, but you can see what I've done and what you've suggested. They both falsely match against *everything* though, and print the whole log file.. Is there something I'm missing?
    toeslikefingers.com - because you've got too much time on your hands
      Are you sure $username is defined and initialized? Turning on the likes of strict and warnings might help, as it looks like $username is empty/undefined and therefore creating an empty regex which matches everything.
      HTH

      _________
      broquaint

        See, this is what happens when you ask questions for other people. The permissions on the file were screwy, and the guy was teesting it from the command line as root in one instance, while from the web in another. Anyway, good old chmod fixed it. Cheers.
        toeslikefingers.com - because you've got too much time on your hands