Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: sorting entires by date

by Coruscate (Sexton)
on Jan 01, 2004 at 23:06 UTC ( [id://318182]=note: print w/replies, xml ) Need Help??


in reply to sorting entires by date

How about something like this:

use Fcntl ':flock'; open my $fh, '+<', 'images.dat' or die "open failed: $!"; flock $fh, LOCK_EX; seek $fh, 0, 0; my @images; while (<$fh>) { chomp; push @images, [(split /:/)[-1], $_]; } my @ordered = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @images; seek $fh, 0, 0; truncate $fh, 0; print $fh join "\n", @ordered; close $fh;

Update: My brain isn't taking shortcuts today. I like Aristotle's approach of passing the file read directly to map(). Didn't think of it for some reason. So a slightly simplified version:

use Fcntl ':flock'; open my $fh, '+<', 'images.dat' or die "open failed: $!"; flock $fh, LOCK_EX; seek $fh, 0, 0; my @ordered = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { chomp; [(split /:/)[-1], $_] } <$fh>; seek $fh, 0, 0; truncate $fh, 0; print $fh join "\n", @ordered; close $fh;

Replies are listed 'Best First'.
Re: Re: sorting entires by date
by exussum0 (Vicar) on Jan 01, 2004 at 23:21 UTC
    I would advise writting to a temp file and moving that tempfile over the original since moves are closer to atomic as a perl instruction. If someone SIG'd your program in the middle, you may lose data.

    Play that funky music white boy..
      Good point - and to be truly lazy you hide this behind IO::AtomicFile. :)

      Makeshifts last the longest.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-23 20:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found