Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: sorting entires by date

by Coruscate (Sexton)
on Jan 01, 2004 at 23:06 UTC ( #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;


Comment on Re: sorting entires by date
Select or Download Code
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
Node Status?
node history
Node Type: note [id://318182]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (12)
As of 2015-07-06 19:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (81 votes), past polls