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

Hi guys,I am new to perl and am having some trouble with the following:

I have a file that has data which looks like:

#12346

orange

#12345

apple

banana

#12344

pear

I need to sort this data according to the numbers in either the same file or another file so that the output looks like the following:

#12344

pear

#12345

apple

banana

#12346

orange

How do I go about this? thanks in advance.

Replies are listed 'Best First'.
Re: Ordering data in a file.
by toolic (Bishop) on Jun 13, 2013 at 01:16 UTC
    Read data into a hash-of arrays data structure, then sort it:
    use warnings; use strict; my %data; my $key; while (<DATA>) { chomp; if (/#(\d+)/) { $key = $1; } else { push @{ $data{$key} }, $_; } } for my $key (sort {$a <=> $b} keys %data) { print "#$key\n"; print "$_\n" for @{ $data{$key} }; } __DATA__ #12346 orange #12345 apple banana #12344 pear

      Thanks a lot .. it worked instantly!!!
Re: Ordering data in a file.
by hippo (Archbishop) on Jun 13, 2013 at 08:47 UTC

    As an old awk head I would first reach for this simple perl-based approach:

    #!/usr/bin/perl use strict; use warnings; $/ = '#'; print sort (<DATA>); __DATA__ #12346 orange #12345 apple banana #12344 pear

    Note that this uses a lexical sort which somewhat coincidentally works for the given data set. If your actual data set is more varied you will probably need to use a different sorting block.

Re: Ordering data in a file.
by Anonymous Monk on Jun 13, 2013 at 01:39 UTC