macromedia wrote:
> Hi,
Hello,
> I can't seem to get my script to sort properly.
Yes, it is a bit tricky to get right.
> Below is my code along with
> a sample input.txt file. I also have what the output.txt file should look
> like. Also note any duplicate should be striped out
> which seems to work ok.
>
> Something is getting messed up when I have the numerials along with alpha
> etc. I can't seem to get the results of the OUTPUT.TXT file below.
>
> #!/usr/bin/perl -w
>
> require 5.000;
>
> use warnings;
> use strict;
> use POSIX;
>
> my %tags = ();
>
> my $input = $ARGV[0];
> my $output = $ARGV[1];
>
> open (FILE, "< $input") or die "cannot open $input: $!\n";
> while (my $tag = <FILE>) {
> $tag =~ m/<tag id=(\w+)>/;
> $tags{$1} = $tag;
You shouldn't use $1 unless you are sure the pattern matched.
> }
> open (NEWFILE, "> $output");
You should verify that this file opened correctly too.
open (NEWFILE, "> $output") or die "cannot open $output: $!\n";
> foreach my $id ( map { $_->[0] }
> sort { $a->[0] cmp $b->[0] || $a->[7] <=> $b->[7] }
> map { [ $_, ( isdigit( $_ ) ? $_ : 0 ) ] }
> keys %tags )
> {
> print NEWFILE $tags{$id};
Missing a closing } here.
This appears to do what you want:
while ( my $tag = <FILE> ) {
next unless $tag =~ /<tag id=(\d*)([^>]*)>/;
$tags{ sprintf '%04d%s', $1 || 9999, $2 } = $tag;
# if you are expecting numbers larger than 9999 then
# use a larger constant and a larger sprintf format
}
open (NEWFILE, "> $output") or die "cannot open $output: $!\n";
foreach my $id ( sort keys %tags ) {
print NEWFILE $tags{ $id };er
}
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>