in reply to Sorting within a file

use strict; use warnings; my @lines; { local *FILE; open(FILE, "< filename.in") or die("Couln't open input file: $!\n"); chomp(@lines = <FILE>); } my @sorted_lines = map { $_->[0]} sort { $a->[1] <=> $b->[1] } map { /^(\d+)/ && [ $_, 0+$1 ] } # OR: map { no warnings; [ $_, 0+$1 ] } @lines; { local *FILE; open(FILE, "> filename.out") or die("Couln't open output file: $!\n"); local $, = "\n"; print FILE (@sorted_lines); }

Update: Fixed a warning.

Replies are listed 'Best First'.
Re^2: Sorting within a file
by Anonymous Monk on Mar 04, 2005 at 20:42 UTC
    my @lines; { local *FILE; open(FILE, "< filename.in") or die("Couln't open input file: $!\n"); chomp(@lines = <FILE>); } my @sorted_lines = map { $_->[0]} sort ( $a->[1] <=> $b->[1] } map { [ $_, 0+$_ ] } @lines; { local *FILE; open(FILE, "> filename.out") or die("Couln't open output file: $!\n"); local $, = "\n"; print FILE (@lines); } Whats with the curly brackets? Here's what I have tried. It looks like + the file is already ordered alphabetically by id when I used "du -ks + *" but I need it by size which is the numbers. Here's my code, it do +esnt seem to change the order. #Push data into an array die("Cannot open Log file to read from.") unless(open(TAKE, "<unix_list.txt")); while ($line = <TAKE>) { push(@list_all, $line); } close(TAKE); @list_all = sort { $a <=> $b } @list_all; die("Cannot open Log file to write to.") unless(open(NEW, ">unix_list.txt")); print NEW @lines; close(NEW);
    Thanks again...
      Whats with the curly brackets?

      It provides a scope for the local *FILE and the local $,. I don't like variables hanging around too long, especially when they have destructors (like FILE) or have side-effects (like $,).

        ikegami, its complaining about argument "1260896 abadeno" isnt numeric in addition at the "map { $_, 0+$_ }" line...
Re^2: Sorting within a file
by Anonymous Monk on Mar 04, 2005 at 21:04 UTC
    Its still having problems. Error states "Can't use string ("") as an array ref while 'strict ref' is in use at line "map { /^(\d+)/ && $_, 0+$1 }"
      You must have a typo somewhere???