Reputation: 75
I've tried to split string from array and save it back with perl, but it's can't split well. I've store a data to an array @nameInt. Data:
ge-1/1/2.552
ge-1/1/2.561
ge-1/1/2.562
ge-1/1/2.580
ge-1/1/2.582
ge-1/1/2.590
ge-1/1/2.592
ge-1/1/2.640
ge-1/1/2.642
ge-1/1/2.644
ge-1/1/2.650
code:
foreach my $interface(@nameInt){
@sepInt = split /[.]/, $interface;
}
I tried to split and save into new array (@sepInt), but when I tried to print out, it's shows and error
print "name interface: ".$sepInt[0][0]." | vlan id: ".$sepInt[0][1];
Can't use string ("ge-1/1/5") as an ARRAY ref while "strict refs" in use
expected:
name interface: ge-1/1/2 | vlan id: 552
name interface: ge-1/1/2 | vlan id: 561
name interface: ge-1/1/2 | vlan id: 562
...
so on
Upvotes: 1
Views: 183
Reputation: 91375
Use an array of array:
foreach my $interface(@nameInt){
push @sepInt, [ split /[.]/, $interface ];
}
Upvotes: 2
Reputation: 6568
Seeing as you're creating an array, not an array of arrays, I think what you're trying to do is this:
my @array = qw (ge-1/1/2.552 ge-1/1/2.561 ge-1/1/2.562 ge-1/1/2.580 ge-1/1/2.582 ge-1/1/2.590 ge-1/1/2.592 ge-1/1/2.640 ge-1/1/2.642 ge-1/1/2.644 ge-1/1/2.650);
foreach (@array){
my @sepInt = split(/[.]/);
print "name interface: $sepInt[0] | vlan id: .$sepInt[1]\n"
}
Outputs:
name interface: ge-1/1/2 | vlan id: .552
name interface: ge-1/1/2 | vlan id: .561
name interface: ge-1/1/2 | vlan id: .562
name interface: ge-1/1/2 | vlan id: .580
name interface: ge-1/1/2 | vlan id: .582
name interface: ge-1/1/2 | vlan id: .590
name interface: ge-1/1/2 | vlan id: .592
name interface: ge-1/1/2 | vlan id: .640
name interface: ge-1/1/2 | vlan id: .642
name interface: ge-1/1/2 | vlan id: .644
name interface: ge-1/1/2 | vlan id: .650
Upvotes: 4
Reputation: 371
Welcome to higher-order functions in Perl!
map {split /[.]/, $_} @nameInt
The built-in function map
helps you to get above the trees so you can see the forest. In other words, it helps you focus your attention on what you want to do rather than on intermediate bookkeeping values such as your $interface
and @sepInt
.
...and, hmm, perhaps what you want is a list of pairs of elements.
map {[split /[.]/, $_]} @nameInt
Upvotes: 4
Reputation: 5664
On each iteration of this loop:
foreach my $interface(@nameInt){
@sepInt = split /[.]/, $interface;
}
you replace @sepInt
with the newly split line. @sepInt
is always an array of strings. So when you get to
print "name interface: ".$sepInt[0][0]." | vlan id: ".$sepInt[0][1];
Can't use string ("ge-1/1/5") as an ARRAY ref while "strict refs" in use
$sepInt[0]
is a string, not an array.
Did you mean to use $nameInt[0][0]
there?
Upvotes: 0