I am seeing strange problem..can someplease please help. I have a log template that looks like this
开发者_StackOverflow中文版 CPU load: 0
Memory load: 7
User load: 0
Interface Information:
eth0: Up
eth1: Up
Processes Information:
Now, I login to my device and get the logs like my @output = $ssh->exec("show details"); The output looks similar, as show below but different values for parameters
CPU load: 21
Memory load: 27
User load: 21
Interface Information:
eth0: Down
eth1: Up
Processes Information:
First I am opening the template file, split it into line by line and when I try to compate it with "show details" output, for the matches, I am getting value 1 as result and not the matched string. Can someone please help.
Code:
my @output = $ssh->exec("show details");
open (FH, "templates/SHOW.txt") || die "Could not open File: $!\n";
@file_array = <FH>;
@TemplateArray = split(/\n/,@file_array);
@matches = split(/\n/,@output);
foreach $keys (@matches) {
foreach (@TemplateArray) {
$keys =~ m/($_)/;
unshift (@result_array, $1);
}
}
print "\n @result_array\n";
}
I get "1" as result but no string.
When you use split
on an array, the array will be in scalar context, and will only return the number of elements in it. In other words:
@TemplateArray = split(/\n/,@file_array);
@matches = split(/\n/,@output);
is equal to:
@TemplateArray = $#file_array;
@matches = $#output;
Which is why you get "1" as a result.
Also, if you are not already doing it:
use strict;
use warnings;
Adding to TLP's answer, the solution is to change
@matches = split(/\n/,@output);
to
@matches = map { split(/\n/, $_) } @output;
so split()
operates on strings from @output
.
split
's expects a string for its second argument, so
@TemplateArray = split(/\n/, @file_array);
ends up being the same as
@TemplateArray = split(/\n/, scalar(@file_array));
Keep in mind that scalar(@file_array)
returns the number of elements in the array.
@file_array = <FH>;
will populate @file_array
as follows:
@file_array = (
"line1\n",
"line2\n",
"line3\n",
);
In other words, it's already split into lines. If you're trying to remove the trailing newlines, you want to replace
@TemplateArray = split(/\n/,@file_array);
with
chomp( my @TemplateArray = @file_array );
I can't help you fix
@matches = split(/\n/,@output);
because I don't know what $ssh
contains, and thus I don't know what @output
contains.
Please use
use strict;
use warnings;
精彩评论