develooper Front page | perl.beginners | Postings from September 2009

Re: push and split

Thread Previous | Thread Next
From:
Uri Guttman
Date:
September 17, 2009 12:42
Subject:
Re: push and split
Message ID:
877hvxe4uq.fsf@quad.sysarch.com
>>>>> "SB" == Steve Bertrand <steve@ibctech.ca> writes:

  SB> Another thing, as Chas pointed out, hashes are unorganized, which means
  SB> that the order of retrieval is almost always different than the order of
  SB> insertion:

just to clarify that, there is no order of retrieval of hash keys, it
appears to be random. but at any given moment a hashes keys will always
be in the same order so you can call any of the hash iterators (keys,
values, each) and get the same order. this is very useful in hash
slicing and other tricks.

  SB> while ( my $entry = <DATA> ) {

  SB>     my ( $router, $ip ) = split /\s+/, $entry;

  SB>     next if ! defined $ip;

how would $ip not be defined if the split works? a simpler boolean test
is likely all that is needed. also unless is cleaner
IMO:

	next unless $ip

  SB>     $router_hash{ $router } = $ip;
  SB> }

one idea is to push all ip addresses onto an anon array keyed by the
router name. this is if you want all the ips for a router and not just
the last one seen.

  SB> while ( my ( $router, $ip ) = each %router_hash ) {

  SB>     print "$router => $ip\n";

  SB> }

here is a little trick i like to do when dumping hashes. it is faster as
it only calls print once.

	print map "$_ => $router_hash{$_}\n", keys %router_hash

it may use up more ram but that is only a problem with large hashes and
you are not likely going to print those. also you can sort the keys if
you want that which is harder to do with each.

also using Data::Dumper is great for this and for debugging any data
trees you need to work with.

uri

-- 
Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About