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

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

i'm printing a new line into a file and then i sort it and print it back onto itself. i'm using the following code for the sorting and printing:

## sort the new list of virtusers open(FH, $virttmp); @virtusers = <FH>; close(FH); ## write sorted file contents back onto itself open(FH, ">$virttmp"); print FH (sort @virtusers); close(FH);

this seems neat enough, but is there a quicker way to do this? i dont believe that sort can be used on a filehandle, but is this really the most efficient way to get the desired results?

humbly -c

Replies are listed 'Best First'.
Re: Sorting a file and printing it back onto itself
by Chady (Priest) on Nov 17, 2001 at 20:00 UTC

    I think you can minimize multi-opening files by opening once:

    open FH, "+>>$virttmp" or die "Cannot open file: $!\n"; seek FH, 0, 0; my @v = <FH>; seek FH, 0, 0; truncate $virttmp, 0; print FH sort @v; close FH;

    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/
Re: Sorting a file and printing it back onto itself
by Zaxo (Archbishop) on Nov 17, 2001 at 22:44 UTC

    I'd recommend safety over speed in this. You may not need to lock your file or make a backup, but it's good policy.

    After Compline,
    Zaxo

Re: Sorting a file and printing it back onto itself
by kwoff (Friar) on Nov 18, 2001 at 04:53 UTC
    One-liner :)
    $ perl -i.bak -0777pe'$_=join"\n",sort(split /\n/),""' users.dat $ cat users.dat.bak me you them she he it we $cat users.dat he it me she them we you