Search code examples
perlshellcisco

How to Split String with 2 Foreach Perl


Hello I have a perl script that connected to cisco router

the actual output if not splited like this

show int desc
Interface                      Status         Protocol Description
Gi1/0/0                        up             up       TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS)
Gi1/0/0.23                     up             up       VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077

then i put my code into this script like this

my @output1 = split(/\s{2,}/, $output);

foreach my $output2 (@output1) {
 $output3="$output2%";
 my @output4 = split(/\s{2,}/, $output3);
  foreach my $output5 (@output4) {
   print "$output5#"
 }
}

why the print out like this

show int desc
Interface%#Status%#Protocol Description
Gi1/0/0%#up%#up%#TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS)
Gi1/0/0.23%#up%#up%#VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077

i want print out like this

show int desc#Interface%Status%Protocol%Description#Gi1/0/0%up%up%TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS)#Gi1/0/0.23%up%up%VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077#

i want a 2 space or more, splited with %, and /n are splited with # thanks for the help


Solution

  • Perhaps because you have not chomped your lines? Also, you're adding both # and % to each line with those nested for loops. Your second split statement is identical to the first, what makes you think it does anything at all?

    If all you want to do is replace whitespace and newline, why not just do that?

    $output =~ s/\n+/#/g;
    $output =~ s/\s{2,}/%/g;
    print $output;
    

    Also, you should know that it is horrible practice to name your variables $output2, $output3 ... $output5.