Re: Perl forgets variable every other pass in loop???



On Aug 27, 4:23 pm, David Filmer <use...@xxxxxxxxxxxxxxx> wrote:
Greetings!

Kindly consider this code which illustrates my question:

#!/usr/bin/perl
use strict;

my $column_ref = [
{ 'description' => { 'align' => 'left' } },
{ 'total' => { 'align' => 'right' } },
];
for (1..6) {
foreach my $format_ref( @{$column_ref} ) {
my( $column, $attr_ref ) = each %{ $format_ref };
print "'$column', '$attr_ref'\t";
}
print "\n";
}
__END__

What I would EXPECT to see from this program is something like this:

'description', 'HASH(0x8206710)' 'total', 'HASH(0x81fd314)'
'description', 'HASH(0x8206710)' 'total', 'HASH(0x81fd314)'
'description', 'HASH(0x8206710)' 'total', 'HASH(0x81fd314)'
'description', 'HASH(0x8206710)' 'total', 'HASH(0x81fd314)'
'description', 'HASH(0x8206710)' 'total', 'HASH(0x81fd314)'
'description', 'HASH(0x816dc28)' 'total', 'HASH(0x8192258)'

But, for some strange reason, Perl seems to "forget" the value of
$column_ref on every OTHER pass. What I ACTUALLY see is this:

'description', 'HASH(0x816dc28)' 'total', 'HASH(0x8192258)'
'', '' '', ''
'description', 'HASH(0x816dc28)' 'total', 'HASH(0x8192258)'
'', '' '', ''
'description', 'HASH(0x816dc28)' 'total', 'HASH(0x8192258)'
'', '' '', ''

Can anyone tell me what is happening to $column_ref???




You're missing the inner most loop. To obtain the output you
desired, you should have written:

for (1 .. 6) {
for my $format_ref (@$column_ref) {
while (my ($c, $a) = each %$format_ref)
{
print "'$c', '$a'\t";
}
}
print "\n";
}


See 'perldoc -f each' -- you're incrementally
going through an iterator and printing the contents
of the null array that's returned when the
iterator is exhausted (on every other line).

--
Hope this helps,
Steven
.



Relevant Pages

  • Re: need help on need help on generator...
    ... A generator function, ... way to make sure you have an iterator is to call iteron something; ... > there's such a thing in Python (... ... My prediction is that even Python 3000 will be strict. ...
    (comp.lang.python)
  • List::MoreUtils::each_arrayref: "semi-panic: attempt to dup freed string"
    ... Kindly consider, if you will, the following code which illustrates my ... question about List::MoreUtils (which reminds me, ... Tassilo around here recently)... ... use strict; use warnings; ...
    (comp.lang.perl.misc)
  • Perl forgets variable every other pass in loop???
    ... Kindly consider this code which illustrates my question: ... use strict; ... But, for some strange reason, Perl seems to "forget" the value of $column_ref on every OTHER pass. ... David Filmer ...
    (comp.lang.perl.misc)