Why does Tie::File add a line if a file is sorted?
Asked Answered
C

2

7

I have this little perl script that is supposed to sort a file:

#!/usr/bin/perl
use strict;
use warnings;

use Tie::File;

tie my @lines, 'Tie::File', 'fileToBeSorted.txt' or die $!;

printf "line count before: %d\n", scalar @lines;

@lines= sort @lines;

printf "line count after: %d\n", scalar @lines;

untie @lines;

When run with this input (fileToBeSorted.txt)

one;4;1
two;3;2
three;2;3
four;1;4

the script outputs

line count before: 4
line count after: 5

and indeed, the sorted file contains an empty fifth line. Why is that and how can I prevent that?

Checkered answered 2/4, 2013 at 20:51 Comment(1)
Don't know, but a workaround is to do sort grep { $_ } @linesNewberry
M
6

As mentioned in a now deleted answer, this seems to be a known bug.

A temporary assignment to an untied list variable is a workaround

my @dummy = sort @lines;
@lines = @dummy;

but this still smells like a bug to me, and you should report it.

Update: Already reported (by our own ikegami, no less). Perlmonks discussion here.

Mogador answered 2/4, 2013 at 21:0 Comment(2)
Nice find on the report. +1Translatable
Credit @Squeezy's deleted answer for links to bug report and perlmonks.Mogador
G
2

As mentioned in the related PerlMonks discussion, @lines = ((), sort @lines); can be used to work around the bug.

Gravamen answered 2/4, 2013 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.