in reply to Array insertion problem

The problem lies in this bit of code:
if ($i == 3) { for ( sort { $a->[1] <=> $b->[1] } @array ) { print "$_->[0]|"; } @array=(); $i =0; } else { $i++; }
Which is FWICT is counting lines, and when then sorting when $i==3 or every third line, and then printing the sorted array (which at the time contains ["llp", 1], ["Up", 5], [0, 6]), so the sorting works as expected. What you probably want is something along the following lines:
#!/usr/perl/bin use strict; my @words; my @array; my $i = 0; while(<DATA>) { if (/^printer/) { if ( @array ) { for ( sort { $a->[1] <=> $b->[1] } @array ) { print "$_->[0]|$_->[1]\n"; } @array=(); $i =0; } my @strings = (split)[1,3,4]; if ( $strings[1] eq "idle." ) { push @array, [ "0", 6 ]; } if ( $strings[2] eq "enabled" ) { my $s = "Up"; push @array, +[ $s, 5 ]; } push @array, [ $strings[0], 1 ]; } elsif (m|Interface:(.+)|i) { @words = split(/\//, $_); chomp($words[-1]); push @array, [ $words[-1], 3]; } elsif (m|Description: (.+)|i) { push @array, [ $1, 4]; } elsif (m|Connection: (.+)|i) { if ($1 eq "direct" ) { push @array, [ "local", 8]; } else { push @array, [ "remote", 8]; } } elsif (/Banner not required/) { push @array, ["No",7 ]; } } for ( sort { $a->[1] <=> $b->[1] } @array ) { print "$_->[0]|"; } __DATA__ printer llp is idle. enabled since Wed Oct 23 15:54:08 GMT 2002. avail +able. Form mounted: Content types: any Printer types: unknown Description: OPENprint printer llp Connection: direct Interface: /usr/lib/lp/model/standard On fault: write to root once After fault: continue Users allowed: (all) Forms allowed: (none) Banner not required Character sets: (none) Default pitch: Default page size: Default port settings: -opost printer ps is idle. enabled since Wed Oct 23 15:54:17 GMT 2002. availa +ble. Form mounted: Content types: postscript, simple Printer types: unknown Description: local printer Connection: direct Interface: /usr/lib/lp/model/net_lj4x On fault: write to root once After fault: continue Users allowed: (all) Forms allowed: (none) Banner not required Character sets: (none) Default pitch: Default page size: Default port settings:
Update:I agree with sauoq. I would think that storing all the data in a hash and then printing at the end would be a much better approach.

-enlil

Replies are listed 'Best First'.
Re: Re: Array insertion problem
by kirk123 (Beadle) on Dec 11, 2002 at 02:31 UTC
    Thanks