Reputation: 13
I have a perl script that telnets to some network equipment, runs a command to gather some card information and returns each line into an array which i then map into a hash. What i am looking to do is perform a regex to grab the card numbers at the beginning of each string value in the hash and push them into an array. But, only half of them...Because each card in the equipment is doubled in the ouput because of the way the vendor returns the information after the command.
The following is @output, the output seen after running the command.
1/1 1187100L1 , Combo A2+ AE.
1/4 1187100L2 , Combo A2+ K.
1/5 1187100L1 , Combo A2+ V
1/16 1187100L2 , Combo A2+ K
1/1 1187100L1 , Combo A2+ No Alarms
1/4 1187100L2 , Combo A2+ No Alarms
1/5 1187100L1 , Combo A2+ No Alarms
1/16 1187100L2 , Combo A2+ No Alarms
There is a portion that divides the scalar value of the @output array by half. What i want to do is perform a $hash{} retrieval and auto increment that by the number of the scalar /2.
I only want to retrieve the first 4 card numbers, 1/1, 1/4, 1/5 and 1/16.
Any suggestions?
Here the part of my code i need help with:
if (@output) {
@ccl = grep ( /Combo/, @output );
my %hash = map { ++$shn => $_ } @ccl;
my $an = scalar(@ccl) / 2;
if ( $hash{0} =~ /^(\d+\/\d+)/ ) {
push( @numbers, $1 );
print "@numbers\n";
}
}
The above works fine, but only for the first value in the hash. I want to run this for only half of the values in the hash.
Upvotes: 0
Views: 102
Reputation: 126742
From what you have written I think this is what you want. It pulls the card number from each line and uses the %seen
hash to push it onto @numbers
if it is the first time it has appeared.
use strict;
use warnings;
my @output = <DATA>;
my @numbers;
my %seen;
for (@output) {
next unless /Combo/i;
my ($card) = /(\S+)/;
push @numbers, $card unless $seen{$card}++;
}
use Data::Dump;
dd \@numbers;
__DATA__
1/1 1187100L1 , Combo A2+ AE.
1/4 1187100L2 , Combo A2+ K.
1/5 1187100L1 , Combo A2+ V
1/16 1187100L2 , Combo A2+ K
1/1 1187100L1 , Combo A2+ No Alarms
1/4 1187100L2 , Combo A2+ No Alarms
1/5 1187100L1 , Combo A2+ No Alarms
1/16 1187100L2 , Combo A2+ No Alarms
output
["1/1", "1/4", "1/5", "1/16"]
Upvotes: 1
Reputation: 781716
This will run your code for the first half of the values in the hash.
foreach my $i (0 .. $an-1) {
if ( $hash{$i} =~ /^(\d+\/\d+)/ ) {
push( @numbers, $1 );
}
}
print "@numbers\n";
BTW, it seems strange to create a hash by mapping incrementing numbers to the values. That's essentially an array, so why not just use the array?
Upvotes: 1