Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Ordering data in a file.

by tracer (Initiate)
on Jun 13, 2013 at 00:56 UTC ( [id://1038642]=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1038642]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-19 16:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found