• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1050
  • Last Modified:

Not a HASH reference

Hi.  I'm getting a Perl error which I'm having trouble solving.  I've cut-down my Perl script to just a testcase of the problem (see attached code).  The final for-loop generates a Perl error saying "Not a HASH reference".  So something's going wrong inbetween copying the array-of-hashes to the main hash, and copying it back out again.  It's probably easier to look at the comments in the testcase code to see what I'm doing.

Thanks for any help with this,
Dan.

#!/usr/bin/perl
use strict;
use warnings;

# Create an array of hashes.

my @chapter_array;

my %chapter1 = ('title' => 'Chapter 1', 'chapter_index' => '1');
my %chapter2 = ('title' => 'Chapter 2', 'chapter_index' => '2');

push(@chapter_array, \%chapter1);
push(@chapter_array, \%chapter2);

# Add chapter array (array of hashes) to a new "main" hash.
my %options = ('chapters' => \@chapter_array);

# Note that this works as expected:
foreach(@chapter_array)
{
	print $_->{'title'} . "\n";
}

##################################################
##################################################
##################################################

# Get the chapters (array of hashes) from our "main" hash.
my @chapters = \$options{'chapters'};

# This doesn't work.
foreach(@chapters)
{
	print $_->{'title'} . "\n"; # This fails with "Not a HASH reference"
}

Open in new window

0
Dracan
Asked:
Dracan
1 Solution
 
zlobchoCommented:
HI.
Try to change this line:

my @chapters = \$options{'chapters'};


to

my @chapters = @{$options{'chapters'}};  
0
 
DracanAuthor Commented:
Great!  Thanks for that :-)
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now