Reputation: 69
How to do the below mentioned pattern match?
Below input is in an array:
@array=("gs : asti:34:234", "gs : asti:344:543:wet");
I used foreach loop
so that I split them and I'm pushing them into an array.
Help me in resolving the below issue.
foreach(@array)
{
if($_ =~ /gs/ig)
{
my @arr2 = split(":",$_); #Splitting the matched pattern
push(@y,$arr2[1]);
}
}
Acutal output is: asti , asti
Desired/Expected Output : asti:34:234 , asti:344:543:wet
Upvotes: 1
Views: 49
Reputation: 4709
You can do it in this way, split strings in only two parts:
use strict;
use warnings;
my @array=('gs : asti:34:234', 'gs : asti:344:543:wet');
foreach(@array)
{
if($_ =~ m/gs/ig)
{
my @arr2 = split(":", $_, 2);
$arr2[1] =~ s/^\s+//; #to remove the white-space
push(my @y,$arr2[1]);
print "@y\n";
}
}
Output:
asti:34:234
asti:344:543:wet
Upvotes: 0
Reputation: 4800
Using a regex capture instead of split can simplify the code, you're already using a regex anyway so why not save a step:
my @array = ("gs : asti:34:234", "gs : asti:344:543:wet");
my @y = ();
foreach my $e (@array) {
push @y, $1 if $e =~ m/^gs : (.*)$/i;
}
Upvotes: 1