Re: Perl forgets variable every other pass in loop???
- From: "attn.steven.kuo@xxxxxxxxx" <attn.steven.kuo@xxxxxxxxx>
- Date: Wed, 27 Aug 2008 17:42:34 -0700 (PDT)
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
.
- References:
- Perl forgets variable every other pass in loop???
- From: David Filmer
- Perl forgets variable every other pass in loop???
- Prev by Date: Perl forgets variable every other pass in loop???
- Next by Date: Re: Perl forgets variable every other pass in loop???
- Previous by thread: Perl forgets variable every other pass in loop???
- Next by thread: Re: Perl forgets variable every other pass in loop???
- Index(es):
Relevant Pages
|