[Melbourne-pm] passing arrays and hashes

Andrew Savige ajsavige at yahoo.com.au
Mon Aug 6 04:57:57 PDT 2007

--- Tim Connors <tconnors at astro.swin.edu.au> wrote:
> I thought I was doing the proper thing by passsing a reference to a hash 
> and dereferncing it in a function, rather than passing the entire hash 
> around the place all the time.
> sub blah($$$) {
>   my ($file,$md5sum,$trashmd5p)=(@_);
>   my %trashmd5=%$trashmd5p;
> ...
> }

As noted in Perl Best Practices, chapter 9, it is best to NOT use subroutine


Luckily, chapter 9 is the free download chapter and section 9.10 of this
excellent book explains why. I strongly recommend this book.
> I think I can see why passing the reference is slow -- perl wants to go 
> through and create a whole new hash in this stage creating a duplicate 
> reference to every item in %$trashmd5p:
>   my %trashmd5=%$trashmd5p;

Yes that would create a copy. Here is how I would write it:

  sub blah {
    my ($file,$md5sum,$trashmd5p)=(@_);
    # example code to print the hash ...
    for my $k (sort keys %$trashmd5p) {
       print $k, " ", $trashmd5p->{$k}, "\n";
    # ...

Done this way, you pass the hash by reference and no copy is made.
In particular, note the $trashmd5p->{$k} notation, nicely suggested
already by Brendon Oliver (aka TUGS).

For more information on Perl references, see:


References are also described in many Perl books. I remember a particularly
good explanation in the good ol' "shiny ball" book, Effective Perl Programming:


Though quite old now, this remains an excellent book. I fondly remember this
book as the one that helped me stop writing Perl in C style and start using
native Perl idioms effectively.


Yahoo!7 Mail has just got even bigger and better with unlimited storage on all webmail accounts. 

More information about the Melbourne-pm mailing list