Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Looping Over Hash Skips an Element?

by Lotus1 (Chaplain)
on Jan 06, 2012 at 18:28 UTC ( #946641=note: print w/ replies, xml ) Need Help??


in reply to Looping Over Hash Skips an Element?

I'm wondering why you need a hash. You are indexing anyway so why not just have two arrays, one for the keys and one for the values.

Another thing I notice is that your keys contain an index. Why not use that number as the index for an array that holds the values? When you need to print you can add the Gi3 part in the print statement. An array would let you do the sum of 8 (or more) values at a time. $sum=$a[$n]+$a[$n+1]+ ... You could use a c style for loop to iterate through every 8th index.


Comment on Re: Looping Over Hash Skips an Element?
Download Code
Re^2: Why not using an array?
by pklausner (Scribe) on Jan 10, 2012 at 13:22 UTC
    From them names I guesstimate he populates this table from the SNMP interface MIB. The index of the ifTable is not necessarily contiguous. Some devices give you 1,2,3.. then jump to 100 or even 1000. So that is not practical as array index. I had the same problem and solved it with hashes plus a custom sort function:
    sub sort_by_intf # sort interface alpha/number name mixture properly { my $A = $a; # just turn any number into a 0004 digit one my $B = $b; $A =~ s/([0-9]+)/ sprintf "%04d",9999-$1 /ge; $B =~ s/([0-9]+)/ sprintf "%04d",9999-$1 /ge; $B cmp $A; # reverse order happens to be useful here: } # Tun0, Ser1, Port-channel2, Gi3, Fa4, Eth5
    Then whenever you loop over the keys, just sort them with that function like so:
    for (sort sort_by_intf keys %ifSpeed) { printf "intf: %s, speed: %d\n" $_, $ifSpeed{$_}; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://946641]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-07-14 07:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (256 votes), past polls