Search code examples
perltie

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


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?


Solution

  • 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.