Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Sorting a file and printing it back onto itself

by c (Hermit)
on Nov 17, 2001 at 19:27 UTC ( [id://126022]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://126022]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2024-04-25 11:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found