Link to home
Start Free TrialLog in
Avatar of vi_srikanth
vi_srikanth

asked on

Perl - Regular Expression - List

Hi friends

I've a list of text which should be matched, and then get replaced by another list of text.  For eg., the first list will be "0,1,2,3" and the second list would be "Zero,One,Two,Three".  Is there any SINGLE pattern with which I can do this?  If so please tell me.

E.g:
Input:  This is 0 test and 1 test.
Output: This is Zero test and One test.

Thanks
Srik
Avatar of zerofill
zerofill

Here is an example code.
Let's say you have the two lists stored in two arrays - @first and @second

@first=("0", "1", "2");
@second=("zero", "one", "two");

$string="This is 0 test and 1 test.";
$counter=0;
foreach $element (@first)
{
$string=~ s/$first[$counter]/$second[$counter]/g;
$counter++;
}
print "$string"; #will print This is Zero test and One test.

NOTE: you must ensure that @first and @second have equal number of elements in order this to work

Good Luck
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vi_srikanth

ASKER

Hi OZO,

It works precisely.  Thanks a lot.  I was looking for such a code ONLY.

But, I'm unable to figure out the meaning for the code-part:

@sub{@first}=@second;

"sub" is a hash array, but you've used "@sub" instead of "%sub".  Also, if I try the same code by changing @sub to %sub, I'm getting a compiler error.  Could u please help me?

Thanks
Srik
@sub{@first} = @second

says to assign multiple values (@second) to multiple keys (@first) in the hash %sub.  My guess is that the @sub{} syntax was chosen to indicate that it is acting as a list and can be assigned to as such where %sub usually indicates hash "mode" where you must assign key => value pairs to it.
Thank You friends.

It is really weird & odd to have @sub to represent a hash array!!!  I'm really finding difficult to digest this.  Thanks again.

Bye
Srik