http://qs1969.pair.com?node_id=11137683

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

Hi,

The code below used to work but now I'm getting the error "Use of uninitialized value in sprintf at test.pl line 72, <FILE> ...". I don't understand what the issue is or how to fix it. It's suppose to take the input file "input.txt" and sort the value of TAGID then write the results to "output.txt". This was written by someone else at the time.

It should open the input.txt file, remove any duplicates, sort with numerials first and then alpha (see sample output file), and write results to output.txt

It's giving the error on this line:

$tags{sprintf("%04d%6s",$1 || 999,$2)} = $tag;

Syntax:

>perl test.pl input.txt output.txt

input.txt:

<tagid=1>Test.</tag>
<tagid=16ab>Test.</tag>
<tagid=aa>Test.</tag>
<tagid=16zz>Test.</tag>
<tagid=39a>Test.</tag>
<tagid=cc>Test.</tag>
<tagid=de>Test.</tag>
<tagid=16bc>Test.</tag>
<tagid=zz>Test..</tag>
<tagid=2>Test.</tag>
<tagid=3>Test.</tag>
<tagid=4>Test.</tag>
<tagid=5>Test.</tag>
<tagid=5a>Test.</tag>
<tagid=5za>Test.</tag>
<tagid=6>Test.</tag>
<tagid=40>Test.</tag>
<tagid=41>Test.</tag>
<tagid=40>Test.</tag>
<tagid=45>Test.</tag>
<tagid=10ba>Test.</tag>
<tagid=15xx>Test.</tag>
<tagid=cc>Test..</tag>
<tagid=ff>Test..</tag>
<tagid=50>Test.</tag>
<tagid=54>Test.</tag>
<tagid=7>Test.</tag>
<tagid=8>Test.</tag>
<tagid=16yy>Test.</tag>
<tagid=16ya>Test.</tag>

output.txt

<tagid=1>Test.</tag>
<tagid=2>Test.</tag>
<tagid=3>Test.</tag>
<tagid=4>Test.</tag>
<tagid=5>Test.</tag>
<tagid=5a>Test.</tag>
<tagid=5za>Test.</tag>
<tagid=6>Test.</tag>
<tagid=7>Test.</tag>
<tagid=8>Test.</tag>
<tagid=10ba>Test.</tag>
<tagid=15xx>Test.</tag>
<tagid=16ab>Test.</tag>
<tagid=16bc>Test.</tag>
<tagid=16ya>Test.</tag>
<tagid=16yy>Test.</tag>
<tagid=16zz>Test.</tag>
<tagid=39a>Test.</tag>
<tagid=40>Test.</tag>
<tagid=41>Test.</tag>
<tagid=45>Test.</tag>
<tagid=50>Test.</tag>
<tagid=54>Test.</tag>
<tagid=aa>Test.</tag>
<tagid=cc>Test.</tag>
<tagid=de>Test.</tag>
<tagid=ff>Test..</tag>
<tagid=zz>Test..</tag>

Code:

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/<x id=(\d*)([[:alpha:]]*)>/; $tags{sprintf("%04d%6s",$1 || 999,$2)} = $tag; } open (NEWFILE, "> $output"); foreach my $id ( sort keys %tags ) { print NEWFILE $tags{$id}; } close NEWFILE; close FILE;