Front page | perl.beginners |
Postings from March 2003
Re: substring problems
Thread Previous
|
Thread Next
From:
Rob Dixon
Date:
March 19, 2003 15:30
Subject:
Re: substring problems
Message ID:
20030319233003.33051.qmail@onion.perl.org
Tao Wang wrote:
> thanks a lot. But there is one problem - this is my
> fault. The KEY1, KEY2 don't exactly look like this.
> There are six KEYS. Three are related to KEYS, but the
> rest of them are A_BEG A_END, B_OPTIONS, and I need to
> extract information between them. I used one variable
> $op=KEY1|KEY2|KEY3|A_BEG|A_END|B_OPTIONS to store all
> the alternatives, and tried to use
>
> my @values = $line =~ /$op.*$op/g;
>
> But didn't work as i expected. Are there any
> problems. please help me with it. thanks again.
Hi Tao.
Your solution is a good one, but the problem is the resulting
regex:
/$op.*$op/
is
/KEY1|KEY2|KEY3|A_BEG|A_END|B_OPTIONS.*KEY1|KEY2|KEY3|A_BEG|A_END|B_OPTIONS/
which will match any of the strings between the pipes:
A_BEG
A_END
B_OPTIONS
B_OPTIONS.*KEY1
KEY1
KEY2
or KEY3
which isn't quite what you had in mind! You could make it work with
some parentheses, but I think it's cleaner using John's 'split' method.
Here's another program which builds the regex for you and processes
your original data. The 'undef' on the left of the assignement serves
to discard the blank initial field before the first key. Note also that
all the spaces are still in the data. It's easy enough to get rid of them,
but without knowing what you want to do with them after this stage
I thought it best to leave things as they are.
HTH,
Rob
#!perl
use strict;
use warnings;
my $keys = join '|', qw ( KEY1 KEY2 KEY3 A_BEG A_END B_OPTIONS );
while (<DATA>) {
chomp;
my (undef, @data) = split $keys;
print ">$_<\n" foreach @data;
print "\n";
}
__DATA__
KEY1 3 4 T KEY2
KEY1 3 4 T KEY2 456 67 KEY3
KEY1 3 4 T KEY2 456 67 KEY3
output:
> 3 4 T <
> 3 4 T <
> 456 67 <
> 3 4 T <
> 456 67 <
Thread Previous
|
Thread Next