Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm trying to populate/create an array of hashes, basics of the code is as follows.
my @day; my @night; my @ip; my $day = "someday"; my $start "some start time"; my $start "some end time"; foreach my $task((qw/day night ip/)){ my %hash=(); $hash{$day}{'start'}=$start; $hash{$day}{'end'}=$end; push @{$task},{%hash}; }
($day, $start and $end are in this case are predefined. In the script they would be defined from values taken from a file)

My understanding of perl and references is a little flaky. What I "assumed" would happen is that the hash (%hash) would be put in to the three arrays @day, @night, and @ip creating an array of hashes. But for some reason they are not.

What I would like to know is
what I need to do to make strict happy without using

no strict "refs";

and
where are the hashes being stored?

Thanks
Mark.

Replies are listed 'Best First'.
Re: trying to use strict :(
by gellyfish (Monsignor) on Jul 16, 2003 at 11:07 UTC

    Essentially you are trying to create a hash-like operation using the horrible symbolic references. I would suggest that you use are real hash with array references as values:

    ... my %tasks = ( day => [], night => [], ip => [] ); ... foreach my $task ( keys %tasks ) { ... push @{$tasks{$task}},\%hash; }
    And then strict will be happy and you will have cleaner code.

    Check out perlref for more on references.

    /J\
    
Re: trying to use strict :(
by davorg (Chancellor) on Jul 16, 2003 at 11:00 UTC

    I'm going to assume that these two lines are just typos.

    my $start "some start time"; my $start "some end time";

    It always helps us if you cut and paste your code into your question rather than trying to retype it.

    Other than that, your problem is the line:

    push @{$task},{%hash};

    You are trying to use $task as a symbolic reference. Symbolic references can be rather dangerous so they are one of the things that use strict marks as illegal.

    I'm not entirely sure what data structure you're trying to build, so I can't really suggest an alternative without more information.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg