On 11-04-06 10:06 AM, Robert Wohlfarth wrote:
On Wed, Apr 6, 2011 at 8:22 AM, Balachandran Sivakumar<benignb...@gmail.com
wrote:

         I am trying to learn hashes in perl. I created an hash
variable with 4 keys. I tried printing the keys in the hash by:(hash
variable is %machines)

foreach $key (keys %machines) {
     print "$key\n";
}


In the perlvar 
documentation<http://perldoc.perl.org/perldata.html#List-value-constructors>,
there's a little blurb that says *Note that just because a hash is
initialized in that order doesn't mean that it comes out in that order. See
sort<http://perldoc.perl.org/functions/sort.html>  for examples of how to
arrange for an output ordering.* It's easy to miss if you didn't know to
look for it.

My limited understanding is that Perl handles the order internally. Code
should never rely on a specific order.


Hash lookups are faster if the keys do not maintain any order. If you add more elements, you will find that the order of the keys will change. One thing Perl does guarantee is that the order of keys and values will be the same provided you do not add or remove anything from the hash. This allows things like this: inserting one hash in another.

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;

# TBD

my %src_hash = (
  a => 1,
  b => 2,
  c => 3,
);

my %dst_hash = (
  x => -1,
  y => -2,
  z => -3,
);

print 'BEFORE: ', Dumper \%src_hash, \%dst_hash;

@dst_hash{keys %src_hash} = values %src_hash;

print 'AFTER: ', Dumper \%src_hash, \%dst_hash;

__END__

--
Just my 0.00000002 million dollars worth,
  Shawn

Confusion is the first step of understanding.

Programming is as much about organization and communication
as it is about coding.

The secret to great software:  Fail early & often.

Eliminate software piracy:  use only FLOSS.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to