1

I am having a very small difficulty in Perl.

I am reading a text file which for some information. While I read the text file, I select some keys from text; as I read further, I wish to save an array of values for the keys.

See for e.g.

Alpha 1

Something: 2132
Something: 2134

Alpha 2

Something: 2132
Something: 2134

I read the file into an array called lines:

my $h;
my $alpha;
for my $line (@lines){
    if ($line =~ m/Alpha (\d+)/){
        $alpha = $1;
        $h->{$alpha} = (); # create empty array for key?
    }
    elsif ($line =~ m/Something: (\d+)/){
        push($h->{$alpha}, $1);
    }
}

Apparently, it gives me an error:

Type of arg 1 to push must be array (not hash element) at test.pl line 28, near "$1)"
Execution of test.pl aborted due to compilation errors.

Unable to figure this out.

3 Answers 3

4

A hash key value can contain only a scalar. If you want to store an array, then you need to go for array reference.

You can do something like this:

for my $line (@lines){
    if ($line =~ m/Alpha (\d+)/){
        $alpha = $1;
        $h->{$alpha} = []; # create empty array refernece for key
    }
    elsif ($line =~ m/Something: (\d+)/){
        push( @{$h->{$alpha}}, $1);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh great. I've understood it now. Thanks.
Testcase: $alpha may remain undef. Shouldn't that be taken care of?
3

You need to make two changes:

    $h->{$alpha} = [];
                   ** - Create an anonymous array and store 
                        a ref to it in the hash

And

    push(@{$h->{$alpha}}, $1);

because push requires an actual array, and you have an array reference. The @{...} wrapper dereferences the arrayref to an actual array.

Comments

0

As earlier answers say, they are correct. But not perfect. $alpha may remain undef. Hence in order to avoid it please add a check.

my $alpha;
for my $line (@lines){
    if ($line =~ m/Alpha (\d+)/){
        $alpha = $1;
        $h->{$alpha} = []; # create empty array refernece for key
    }
    elsif ($line =~ m/Something: (\d+)/){
        if(defined $apha) { ## Check
           push( @{$h->{$alpha}}, $1);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.