title: How to pass a hash by reference in perl
body: <p>I know this should be easily searchable on google, not to mention a trivial use of perl, but I've tried many solutions I've found and so far none of them gives the expected behavior. Essentially, I'm trying to call a subroutine, return a reference to a hash from that subroutine, pass a reference to that hash to another subroutine, and then print the contents of that hash, via code similar to the following:</p>
  
  <pre><code>#!/usr/bin/perl                                                                                                                                                                                                   
  
  my $foo = make_foo();
  
  foreach $key (sort keys %$foo) {
      print "2 $key $$foo{$key}\n";
  }
  
  print_foo(\%foo);
  
  sub print_foo
  {
      my %loc = ???;
      foreach $key (sort keys %loc}) {
          print "3 $key $loc{$key}\n";
      }
  }
  
  sub make_foo
  {
      my %ret;
      $ret{"a"} = "apple";
      foreach $key (sort keys %ret) {
          print "1 $key $ret{$key}\n";
      }
      return \%ret;
  }
  </code></pre>
  
  <p>Can someone tell me the best way of doing this (via subroutines) without creating an extra copy of the hash? The solutions I've tried have not printed out any lines starting with "3".</p>