0

So I seem to be having trouble passing a hash reference to a subroutine in Perl. I'm attempting to pass the references using prototypes, and I think that may be where the problem is coming from. In short, when dereferencing the hash reference in the subroutine and attempting to print out an array of the keys, the array is empty, while I can confirm that it does contain keys when printed outside of the subroutine.

Forward definition of the subroutine:

sub getEvidenceCodeFilteredHash (\%$);

Subroutine in question. The say functions are to see what's happening in the subroutine, and as of now, only 'ONE' is printing out:

sub getEvidenceCodeFilteredHash (\%$) {
    my ($hashRef, $evidenceCode);
    my %evidenceCodeFilteredHash;
    say "ONE";
    say (keys %{$hashRef});
    foreach (keys %{$hashRef}) {
            say "TWO";
            if ($_ ne '!gaf-version: 2.0') {
                    say "THREE";
                    ${$hashRef}{$_} =~ /^\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?(\S+?)\s.$/;
                    if ($evidenceCode eq $1) {
                            say "FOUR";
                            $evidenceCodeFilteredHash{$_} = ${$hashRef}{$_};
                            say $evidenceCodeFilteredHash{$_};
                    }
            }
    }
    return %evidenceCodeFilteredHash;
}

Calling the subroutine on a hash and a scalar:

my %evidenceCodeFilteredHash = getEvidenceCodeFilteredHash(%commonPairHash, $evidenceCode);

Thanks!

J0HN_TIT0R
  • 323
  • 1
  • 13
  • Your forgot to say `... = @_;` – mob Oct 31 '16 at 01:19
  • Oh my... Well thanks for pointing that out! It's been a long day haha – J0HN_TIT0R Oct 31 '16 at 01:21
  • 1
    As an aside -- [avoid using sub prototypes.](http://stackoverflow.com/questions/297034/why-are-perl-5s-function-prototypes-bad) They are confusing, and are incompatible with object-oriented code. If you need to pass a hash to a function by reference, store it as a hashref, or take a reference (`\%h`) when calling the function. –  Oct 31 '16 at 04:40

1 Answers1

0

You never assigned anything to $hashRef and $evidenceCode. Replace

my ($hashRef, $evidenceCode);

with

my ($hashRef, $evidenceCode) = @_;
ikegami
  • 367,544
  • 15
  • 269
  • 518