Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Sort alphabetically from file

by hippo (Archbishop)
on Jun 14, 2019 at 13:33 UTC ( [id://11101348]=note: print w/replies, xml ) Need Help??

in reply to Sort alphabetically from file

TIMTOWTDI but here is one to get your teeth into.

#!/usr/bin/env perl use strict; use warnings; print sort { ($a =~ /\S+\n$/g)[0] cmp ($b =~ /\S+\n$/g)[0] } <DATA> __DATA__ 1 2 3 delta 1 2 3 apricot 1 2 3 charlie 1 2 3 bravo 1 2 3 echo 1 2 3 fox

Replies are listed 'Best First'.
Re^2: Sort alphabetically from file
by edujs7 (Novice) on Jun 14, 2019 at 14:43 UTC
    Thanks man but for some reason not working - I'm using a .txt file as input to sort BT<W print sort { ($a =~ /\S+\n$/g)[0] cmp ($b =~ /\S+\n$/g)[0] } file.txt not sure if I'm using it correctly

      You have just demonstrated why haukex advised you to "post a question effectively". Your problem now has more to do with reading a file than it does with sorting. You must create a filehandle by opening (open) the file and then read from the filehandle with the diamond operatior <> (perlop). All the answers you have received use the special filehandle DATA which is open by default.

      For additional info on sorting, refer to FAQ How do I sort an array by (anything)?


      You'll need to open the file first. eg:

      open my $in, '<', 'file.txt' or die "Cannot open file for reading: $!" +; print sort { ($a =~ /\S+\n$/g)[0] cmp ($b =~ /\S+\n$/g)[0] } <$in>; close $in;

      See open and close for all the details.

        This worked - thanks so much :)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11101348]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-06-25 00:05 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.