Regular Expression $1?

Y

Yang

I want to get everything between () in the file, say (5), (6), so I
wrote the following:

while(my $line = <FIN>){
chomp $line;
if($line =~ /\(\d*\)/{
print $1;
}
}

But it always returns error saying that $1 is uninitialized.
 
J

Jim Cochrane

I want to get everything between () in the file, say (5), (6), so I
wrote the following:

while(my $line = <FIN>){
chomp $line;
if($line =~ /\(\d*\)/{
print $1;
}
}

But it always returns error saying that $1 is uninitialized.

I think you want:

if ($line =~ /(\(\d+\))/ {
....
}


[CE: not tested.]

--
 
P

Paul Lalli

I want to get everything between () in the file, say (5), (6), so I
wrote the following:

while(my $line = <FIN>){
chomp $line;
if($line =~ /\(\d*\)/{
print $1;
}

}

But it always returns error saying that $1 is uninitialized.

$1 is assigned to whatever is "captured" by parentheses in the pattern
match. You have no capturing parentheses in the pattern match. You
only have the litteral parenthses that you're trying to match. You
need to surround what you want to capture with parentheses:

/\((\d*)\)/

Note that \d* means "0 or more digits" which means an empty () is a
valid match for this expression. If you want to require at least one
digit, change the * to a +.

Paul Lalli
 
C

Cloink

Paul - well done for answering lucidly, it doesn't happen often, esp
not on Perl pages.
 
J

Jeff Stampes

Yang said:
I want to get everything between () in the file, say (5), (6), so I
wrote the following:

Not exactly, the following doesn't compile.
while(my $line = <FIN>){
chomp $line;
if($line =~ /\(\d*\)/{
print $1;
}
}

But it always returns error saying that $1 is uninitialized.

It would be helpful to provide an example of your data as well.

IAC, I won't give you any fish, but here's a line and a pole:

You get the capture variables ($1, $2, $3, etc) by capturing things in
sets of parentheses. Where are the parentheses in your regexp that
would be doing the capturing?

~Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top