-1

Im trying to sort a file based on line length:

my name is tim
I like pineapples alot
hi

into something like this

hi
my name is tim
i like pineapples alot

I have to include whitespaces in there too, so what i have tried doing is putting each line into an array as one line = 1 string in the array. Then I tried to sort the array but that didnt work out too well.

yibs
  • 47
  • 8
  • 2
    Use a string length function for the comparison step of the sort function. – Dave S Mar 21 '18 at 23:25
  • 1
    https://stackoverflow.com/questions/5917576/sort-a-text-file-by-line-length-including-spaces (there's a perl solution near the bottom) – zzxyz Mar 21 '18 at 23:28
  • @DaveS im confused on this could you go into more detail – yibs Mar 21 '18 at 23:30
  • @zzxyz You talking about the one line thing that has perl in it? – yibs Mar 21 '18 at 23:30
  • @yibs https://stackoverflow.com/a/46437608/58074 or https://stackoverflow.com/a/40786477/58074 yes – dsolimano Mar 21 '18 at 23:32
  • Yeah, It does what @DaveS was suggesting. – zzxyz Mar 21 '18 at 23:34
  • @zzxyz im doing an assignment where I have to use a subroutine, i dont think it will count if i do that – yibs Mar 21 '18 at 23:45
  • @yibs - Well, there are subroutines. 2 that you've created and are being called by 'the framework', and one that you've both created AND are calling implicitly in the call to `sort`. But it probably won't count if you have no idea how it works :) – zzxyz Mar 21 '18 at 23:57
  • @zzxyz yea sorry im very new to this. All i was able to do is put each line into an array, so array index 1 would have the first line and so on. Im trying to figure out how to sort it so shortest line is in index 1 and longest is the last , including whitespaces :( – yibs Mar 22 '18 at 00:02

1 Answers1

0

This (from one of the existing "duplicate" answers):

perl -ne 'push @a, $_; END{ print sort { length $a <=> length $b } @a }' file

And this:

#!/usr/bin/env perl

use warnings;
use strict;
my @arr;

sub compareLength
{
        length $::a <=> length $::b;
}

while (<>)
{
        push @arr, "$_";
}
print (sort {compareLength} @arr);

Are basically the exact same thing. -n creates the while(<>), END puts stuff after it, and the comparison function is anonymous (vs named) and inline. (But it still exists and is still a subroutine).

Oh, and I renamed @a to @arr, because I don't like two different variables both named a (@a and $a)

I hope this helps.

zzxyz
  • 2,953
  • 1
  • 16
  • 31
  • No need for all that `push`ing ☺ `perl -e 'print sort { length $a <=> length $b } <>' file` – haukex Mar 22 '18 at 09:41
  • @haukex - Yeah, I deliberately picked a more....explicit? solution. Apparently barely slower, too, which I guess makes sense. – zzxyz Mar 22 '18 at 15:43