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

LVL 1
DracanAsked:
Who is Participating?
 
zlobchoConnect With a Mentor Commented:
HI.
Try to change this line:

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


to

my @chapters = @{$options{'chapters'}};  
0
 
DracanAuthor Commented:
Great!  Thanks for that :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.