Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks , I am reading a file that contain information for employess , the file look like this :
EmpNum LOCATION Shift 23 54 1 11 65 3 23 54 2
what I want to do is read that file and then print some sort of schedule , somthing like:
EmpNum LOCATION shift 23 54 1 54 2 11 65 3
I am not sure how to read the file in an easy way, I was trying somthing like:
While(<DATA>) { next if ($_ =~ /^#/ || $_ =~ /^EmpNum/); push (@EMP, $_); foreach $emp (@EMP) { push (@emp, EMP[#emp]) } }
Can someone help showing me a good way to do it ... thanks a lot

Edit by tye, fix CODE tag as /CODE.

Replies are listed 'Best First'.
Re: complex input file
by Roger (Parson) on Feb 18, 2004 at 04:47 UTC
    Something like this?
    use strict; use warnings; chomp(my @title = split /\s+/, <DATA>); my %emp; while (<DATA>) { chomp(my @r = split/\s+/); push @{$emp{$r[0]}}, [ @r[1..$#r] ]; } foreach (reverse sort keys %emp) { print "$_"; foreach (@{$emp{$_}}) { print "\t$_->[0]\t$_->[1]\n"; } } __DATA__ EmpNum LOCATION Shift 23 54 1 11 65 3 23 54 2
    And the output -
    23 54 1 54 2 11 65 3

    Updated: solution 2
    use strict; use warnings; use Data::Dumper; chomp(my @title = split /\s+/, <DATA>); chomp(my @data = <DATA>); my @sorted_data = map { $_->[1] } sort { $b->[0] <=> $a->[0] } map { [/^(\d+)/, $_] } @data; my $last_emp = ''; foreach my $d (@sorted_data) { $d =~ s/^$last_emp\b/' ' x length($last_emp)/e; $d =~ /^(\d+)/ and $last_emp = $1; print "$d\n"; } __DATA__ EmpNum LOCATION Shift 23 54 1 11 65 3 23 54 2

      thanks much , I like the second since I don't understand Hash table. thanks again Roger
        I thought the second one was more complicated than the first one? :-)

      Roger , I am new to perl . Would you mind explaining this part to me in your first answer :
      print "\t$_->[0]\t$_->[1]\n";
      since if I add one more column in the DATA file , I do this :
      print "\t$_->[0]\t$_->[1]\t$->[2]\n";
      but the output stay the same , I don't get the last column. Sorry for asking tooo many questions
        print "\t$_->[0]\t$_->[1]\t$->[2]\n";

        Contains a typo, it should be:

        print "\t$_->[0]\t$_->[1]\t$_->[2]\n";

        $_ is a special perl variable.