-1

I'm editing a perl code and I added subroutine to which I need to pass a hash.

  %OrigResultHash = Parsing(\%OrigFileHash,\%OrigParamHash);

sub Parsing {

my (%fileHash,%paramHash)=(@ARG);
my %resultHash;
    foreach my $file (keys %fileHash) {
  my (@fileParam)=@{$fileHash{$file}};
  my (@fileStates)=grep(/^state:/,@fileParam);

when running I get the error message:

Not an ARRAY reference at /vobs/cores/periph/blsp_prj/scripts/flow_result_parser_with_flag_orig.pl line 193. which is referring to:

foreach my $file (keys %fileHash) {

Can you explain what is wrong in the code?

user1907831
  • 1
  • 2
  • 2

2 Answers2

1

There are a bunch of issues with your code. First of all, please turn on use strict and use warnings.

  • You are passing your two arguments \%OrigFileHash,\%OrigParamHash as references, which is the right thing to do as they are hashes. But in your sub, you are assigning them to hashes with my (%fileHash,%paramHash)=(@ARG).

    That way, you end up with the a one-key hash in %fileHash and undef in %paramHash.

    print Dumper \%fileHash, %paramHash;
    
    $VAR1 = {
      'HASH(0x5cad8c)' => {
        'xxx' => 'asdf'
      }
    };
    

    As you see, that is not what you want.

  • The actual error message you are talking about it not from the foreach line, though. It's from the line below where you have my (@fileParam)=@{$fileHash{$file}}. As we can see in the above Dumper output, there is no array ref, just as the error message says. This will go away once we fix the assignment problem. You need to assign your referenced params as scalars so the will still be references. You can then dereference them if you prefer to work with hashes. I combined this into the following lines.

    my %fileHash = %{ shift };
    my %paramHash = %{ shift };
    
simbabque
  • 53,749
  • 8
  • 73
  • 136
1

So , where does @ARG come from?Instead ,you should use @_ to get the value transferred to the subroutine.And , what do you mean by my (%fileHash,%paramHash)=(@ARG); ? Perl use hash reference instead of hash body to transfer to the function ,so , you cannot use %fileHash ,but just a scalar value to store the hash ref.So ,change your code to:

%OrigResultHash = Parsing(\%OrigFileHash,\%OrigParamHash);

sub Parsing {

my ($fileHash,$paramHash)=@_;
my %resultHash;
    foreach my $file (keys %$fileHash) {
    my (@fileParam)=$fileHash->{$file};
    .....
wuchang
  • 3,003
  • 8
  • 42
  • 66