Reputation: 75
I'm trying to learn perl for parsing a file, but I got a problem here when parsing a multidimensional array.
>cat files
ge-1/1/1.81 up up NODEB_CLUSTER#81
ge-1/1/1.82 up up NODEB_CLUSTER#82
ge-1/1/1.2501 up up *** OM_nodeB_VLAN_2501 ***
ge-1/1/1.2502 up up *** OM_nodeB_VLAN_2502 ***
if I tried to push it with split spaces, it makes 4 column for first and second row, but 6 column for third and fourth row.
how do we split it and create an output like this:
ge-1/1/1.81,up,up,NODEB_CLUSTER#81
ge-1/1/1.82,up,up,NODEB_CLUSTER#82
ge-1/1/1.2501,up,up,*** OM_nodeB_VLAN_2501 ***
ge-1/1/1.2502,up,up,*** OM_nodeB_VLAN_2502 ***
thank you all
Upvotes: 0
Views: 65
Reputation: 1849
Chomping the array isn't really doing anything good
You can also explicitly match 2 or more spaces:
use warnings;
use strict;
foreach my $line (<DATA>)
{
chomp($line); #remove newline
print join( ',',
split( /\s{2,}/, $line ) #at least 2 spaces
), "\n";
}
__DATA__
ge-1/1/1.81 up up NODEB_CLUSTER#81
ge-1/1/1.82 up up NODEB_CLUSTER#82
ge-1/1/1.2501 up up *** OM_nodeB_VLAN_2501 ***
ge-1/1/1.2502 up up *** OM_nodeB_VLAN_2502 ***
Upvotes: 0
Reputation: 23522
#!/usr/bin/perl
use warnings;
use strict;
my @array = <DATA>;
chomp (@array);
foreach (@array)
{
my @a = split (/\s\s+/,$_);
foreach (@a)
{
print "$_,";
}
print "\n";
}
__DATA__
ge-1/1/1.81 up up NODEB_CLUSTER#81
ge-1/1/1.82 up up NODEB_CLUSTER#82
ge-1/1/1.2501 up up *** OM_nodeB_VLAN_2501 ***
ge-1/1/1.2502 up up *** OM_nodeB_VLAN_2502 ***
OUTPUT:
ge-1/1/1.81,up,up,NODEB_CLUSTER#81,
ge-1/1/1.82,up,up,NODEB_CLUSTER#82,
ge-1/1/1.2501,up,up,*** OM_nodeB_VLAN_2501 ***,
ge-1/1/1.2502,up,up,*** OM_nodeB_VLAN_2502 ***,
Pay attention how I am splitting. You need \s\s+
as there is space between ***
and OM
.
The split will split on 2 spaces or more
. So this way, it will not split *** OM...
as there is only 1 space in between.
Upvotes: 2