functionperlhashhashref

Perl hash reference as argument to subroutine - Can't use string as a HASH ref


I was trying to prepare a small script with hash and subroutine. Honestly Iam a newbie in perl. Can someone tell me whats wrong with the below code. Im getting Can't use string ("1") as a HASH ref error.

#!/usr/bin/perl
use strict;
use warnings;
no warnings 'uninitialized';

use Data::Dumper;
my %match_jobs;

push @{$match_jobs{'1'}},
  {'job_id'=>'13',
   'job_title'=>'Article_9',
   'job_description'=>'899.00'
};

hash_iterate(\%match_jobs);


sub hash_iterate{
  my $job_match=@_;
  print Dumper($job_match);
  foreach my $match_job_row (keys %$job_match) {
    my $job_id_ll=$job_match->{$match_job_row}->{'job_id'};
    print $job_id_ll;
  }
}

Output:- Can't use string ("1") as a HASH ref while "strict refs" in use at perl-hash.pl line 17.

Appreciate you help.!


Solution

  • When you say

    my $job_match=@_;
    

    You're using @_ in scalar context, which gets you the count of elements in the array. You can change that to list-context by saying:

    my ($job_match) = @_;
    

    I personally prefer:

    my $job_match = shift;
    

    shift will, if no array is given, operate on @_. But I guess that's a personal taste question.