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

Hi,

I ran in a strange behaviour of an array: all 4 values pushed in aren't displayed, only the last ones (+). The number of 4 is example only. It could be 1 or more.

Here my code:

open $INPUT, $FileName or die $!; while( <$INPUT> ) { ....... /^($Ref2General->[$i_gdes])/ and do { chomp; s/^($Ref2General->[$i_gdes]:\s+)(.*)//; s/\t+//gm; if ( $2 ) { push( @{ $GeneralInfo{$Ref2General->[$i_gdes]} }, $2); # + #-- Displaying of 4 lines of text still works fine #-- The way is: $Array[ Nbr. ] } else { push @{ $GeneralInfo{$Ref2General->[$i_gdes]} }, $NotNamed; } next; }; ....... /^$Ref2General->[$i_gnoi]/ and do { next if ( $GeneralInfo{$Ref2General->[$i_gnov]} eq $NoSNMP ); my $NodeVendor=$GeneralInfo{$Ref2General->[$i_gnov]}; my $HostName=$GeneralInfo{$Ref2General->[$i_ghos]}; chomp; s/^(\s*$Ref2General->[$i_gnoi]:\s*)(.*)//; $GeneralInfo{$Ref2General->[$i_gnoi]}=$2; foreach my $Key ( keys %GeneralInfo) { $NodeInfo{$NodeVendor}{$HostName}{$Key} = $GeneralInfo{$Key}; } #-- This one for debug tests: foreach my $Key1 ( keys %NodeInfo) { foreach my $Key2 ( keys %{$NodeInfo{$Key1}} ) { foreach my $Key3 ( keys %{$NodeInfo{$Key1}{$Key2}} ) { print $Key3, "\t", $NodeInfo{$Key1}{$Key2}{$Key3}, "\n"; if ( $Key3 eq "DESCRIPTION" ) { # foreach my $val( @{ $NodeInfo{$Key1}{$Key2}{$Key3} } ) +{ print __LINE__, "\t", ${ $NodeInfo{$Key1}{$Key2}{$Key3 +} }[ 0 ] ; print __LINE__, "\t", ${ $NodeInfo{$Key1}{$Key2}{$Key3 +} }[ 1 ] ; # + print __LINE__, "\t", ${ $NodeInfo{$Key1}{$Key2}{$Key3 +} }[ 2 ] ; # + print __LINE__, "\t", ${ $NodeInfo{$Key1}{$Key2}{$Key3 +} }[ 3 ] ; # } print "\n"; } } } } }; ....

The data used is a String of alphanumeric characters and strict is in use

thanx 4 for inspiration,
ChFa

Janitored by Arunbear - replaced font tags with code tags

Replies are listed 'Best First'.
Re: Strange behaviour of an array
by Prior Nacre V (Hermit) on Oct 04, 2004 at 11:32 UTC

    There are three possible problems here.

    Possibility 1

    In the first case you have:

    push( @{ $GeneralInfo{$Ref2General->[$i_gdes]} }, $2); . . . push @{ $GeneralInfo{$Ref2General->[$i_gdes]} }, $NotNamed;

    In the second you have:

    $GeneralInfo{$Ref2General->[$i_gnoi]}=$2;

    Is this related to the problem? Also, you're not checking $2 here (as you are with the previous case).

    Possibility 2

    You are relying on $_ being available and unchanged too deep in your code. Consider using this construct:

    while (my $line = <INPUT>) { . . . }

    Possibility 3

    Similarly, you are expecting values captured in one regex ($1, $2, etc.) to be available after another regex is evalualted. Immediately after the regex, you should either use the captured data straight away, or store the values for later use.

    The inclusion of test data and output results is usually helpful.

    Regards,

    PN5