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

Got some code (see below), where basically I need and array of hash refs, but my named variable is using the same memory location each time. How do I get it (%href) to use a different memory location each time through the loop?
foreach $row (@$rows) {
	
	%hrec = (
		product_id => $row->{'product_id'},
		product_sku => $row->{'product_sku'},
		size_id => $row->{'size_id'},
		size_name => $row->{'size_name'},
		price => $row->{'price'},
		product_name => $row->{'product_name'}
	);
	$num = push @products, \%hrec;
			
}

foreach $product(@products) {
	print "Product SKU:  $product->{product_sku}\n";
	print "Size:  ";
		foreach $size(@{$product->{size_id}}){
			print "$size ";
		}
	print "\n";
	print "Price Each:  \$$product->{price}\n";
}

exit;

Replies are listed 'Best First'.
Re: Needs new memory location
by davorg (Chancellor) on Aug 21, 2000 at 19:11 UTC

    Either use a new variable each time...

    foreach $row (@rows} { my %hrec = ( # etc... }

    or allocate a new anonymous hash each time...

    foreach $row (@rows} { $hrec = { # Note: different bracket # etc... } $num = push @products, $hrec; }
    --
    <http://www.dave.org.uk>

    European Perl Conference - Sept 22/24 2000, ICA, London
    <http://www.yapc.org/Europe/>
      Thanks, I was making it harder than it was...I missed the bracket change too.
      --rjm--
Re (tilly) 1: Needs new memory location
by tilly (Archbishop) on Aug 21, 2000 at 19:13 UTC
    Make sure you create new variables each time. See for loops, closures for discussion. davorg beat me to a code example or I would have given one.