For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > January 2006 > HELP with pattern matchnig ..NEWBIE!!









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author HELP with pattern matchnig ..NEWBIE!!
MegaC

2006-01-23, 6:57 pm

HELP!!! WHAT IS WRONG HERE. I want to pattern match the input from a
file for the string contained in the variable $userName.

sub parseACR_NAR {

my($value) = shift(@_); # gets the ACR record
my(@allLines) = ();
my($temp) = "";

open my $fh, '<', $value or die "Could not open $value: $!";
@allLines = <$fh>;
close $fh;

foreach $temp(@allLines) {
if (/"$userName"/) {
print "found username of $userName\n";
}
}

usenet@DavidFilmer.com

2006-01-23, 6:57 pm

MegaC wrote:
> foreach $temp(@allLines) {
> if (/"$userName"/) {


You are (rightly) using an explicit loop variable ($temp). But your
regexp doesn't bind to this variable, so by default, it is binding to
the default variable $_ (not $temp). If you want to bind a match to a
particular variable, you need to tell Perl which variable, ie:

if ($temp =~ /"$userName"/) {

--
http://DavidFilmer.com

umptious@gmail.com

2006-01-26, 9:55 pm


usenet@DavidFilmer.com wrote:
> MegaC wrote:
>
> You are (rightly) using an explicit loop variable ($temp). But your
> regexp doesn't bind to this variable, so by default, it is binding to
> the default variable $_ (not $temp). If you want to bind a match to a
> particular variable, you need to tell Perl which variable, ie:
>
> if ($temp =~ /"$userName"/) {
>


However, as $userName is a variable, it shouldn't be in quotes AND
inside the //. (In my experiments this failed to work.) The Regexp
tutorial uses the equivalent of simply

if ($temp =~ /$userName/) {

(Although $ is used as a Metacharacter for anchoring a the end of a
line, it doesn't seem to be treated as such unless it appears as the
final character of regexp.)

As I'm still learning Perl I experiemented with the various forms
possible and found:

my $re = "froofy";
print "1 Shouldn't see this\n" if ("hello froofy" =~ /"$re"/);
print "2 Should see this\n" if ("hello froofy" =~ "$re");
print "3 Should see this\n" if ("hello froofy" =~ $re);
print "4 Should see this\n" if ("hello froofy" =~ /$re/);
print "5 Should see this\n" if ("\"froofy\"" =~ /"$re"/);

Ie the // act exactly the same as "" double quotes in interpolating
variables, and their choice as delimiters for regexps is (correct me if
I'm wrong) simply a convention. Of course using // means that double
quotes don't have to be escaped to be used as literals anymore.

Speed reading the regexp docs, I'm not sure that #2 is supposed to work
- I don't see it used anywhere.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com