READFILE sorting coding problem

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I am new to Perl and trying to read a file (employee.txt) that has four col
umns of data. I want to read from the file, print the first and last column
, sorted by the first column. The code I have so far is below but when I ru
n it, I only get a "1 file found" message, no data prints. Your help is gre
atly appreciated.

$i = 0;
@names = open(READFILE, "employee.txt") || die "Couldn't open file: $!";

foreach(sort sort_names (@names))
print("$i records found\n");  

sub sort_names
  $a =~ m/\S*\s*(\S*)/;
  $one = $1;
  $b =~ m/\S*\s*(\S*)/;
  $two = $1;

  $two cmp $one || $b <=> $a;

Re: READFILE sorting coding problem writes:
Quoted text here. Click to load it

This should be

open(READFILE, "employee.txt") || die "Couldn't open file: $!";
@names = <READFILE>;

You want the contents of the file in @names, not the return value of

Re: READFILE sorting coding problem

On 10/25/2013 07:11, wrote:
Quoted text here. Click to load it

Something like this should work:

use strict;
use warnings;

open READFILE, "employee.txt" or die "open employee.txt: $! ($^E)";
my @names = <READFILE>;
chomp @names;

printf "records found = %s\n", scalar @names;

foreach (sort { (split ' ', $a)[0] cmp (split ' ', $b)[0] } @names) {
    print "$i: $_\n" if $debug;
    printf "%s\t%s\n", (split ' ', $_)[0,3];


Re: READFILE sorting coding problem

use strict;
use warnings;
use feature 'say';
#open DATA, '<:utf8', 'somefile.csv' or die "Could not read fiel because  

my $column_to_sort = 1;
my @data;

while (<DATA>) {
/^\s*(\S*)[,\s]*(\S*?)[,\s]*(\d\.\d\.\d)[,\s]*(\S*?)\s*$/ or next;
push @data, [$1,$2,$3,$4];

foreach (sort {$a->[0] cmp $b->[0] || $a->[3] cmp $b->[3]} @data) {
say "@"

name2 , colum1, 444.444.4444, info4
name1 , colum3, 111.111.1111, info2
name1 , colum2, 222.222.2222, info1
name3 , colum4, 333.333.3333, info3

Site Timeline