Perl : get substring which matches regex error
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-04-08T14:44:30Z
Indexed on
2010/04/08
15:13 UTC
Read the original article
Hit count: 535
I am very new to Perl, so please bear with my simple question:
Here is the sample output:
Most successful agents in the Emarket climate are (in order of success):
1. agent10896761 ($-8008)
2. flightsandroomsonly ($-10102)
3. agent10479475hv ($-10663)
Most successful agents in the Emarket climate are (in order of success):
1. agent10896761 ($-7142)
2. agent10479475hv ($-8982)
3. flightsandroomsonly ($-9124)
I am interested only in agent names as well as their corresponding balances, so I am hoping to get the following output:
agent10896761 -8008
flightsandroomsonly -10102
agent10479475hv -10663
agent10896761 -7142
agent10479475hv -8982
flightsandroomsonly -9124
For later processes.
This is the code I've got so far:
#!/usr/bin/perl -w
open(MYINPUTFILE, $ARGV[0]);
while(<MYINPUTFILE>)
{
my($line) = $_;
chomp($line);
# regex match test
if($line =~ m/agent10479475/)
{
if($line =~ m/($-[0-9]+)/)
{
print "$1\n";
}
}
if($line =~ m/flightsandroomsonly/)
{
print "$line\n";
}
}
The second regex match has nothing wrong, 'cause that is printing out the whole line. However, for the first regex match, I've got some other output such like:
$ ./compareResults.pl 3.txt
2. flightsandroomsonly ($-10102)
0479475
0479475
3. flightsandroomsonly ($-9124)
1. flightsandroomsonly ($-8053)
0479475
1. flightsandroomsonly ($-6126)
0479475
If I "escape" the braces like this
if($line =~ m/\($-[0-9]+\)/)
{
print "$1\n";
}
Then there is never a match for the first regex...
So I'm stuck with a problem of making that particular regex work. Any hints for this? Many thanks in advance.
© Stack Overflow or respective owner