I’m Trying to sort letters in a file from A to Z
for example: a A B d r g
sorted: A a B d g r
@ARGV == 2 or die "Usage: $0 infile outfile\n";
open $old, '<', $ARGV[0] or die $!;
open $new, '>', $ARGV[1] or die $!;
@mass=<$old>;
@array=qw(@mass);
@sort=sort @array;
@mass1=sort {uc $a cmp uc $b} @sort;
print $new @mass1;
Where am I going wrong?
I’m not sure what you intended to do with
qw, butsuffice it to say that the contents of
@masswill be never be used.Will cause
@arrayto be defined to contain 2 strings,helloandworld. It is just shorthand for:Which is why
Evaluates to
('@mass')– an array with the single literal string of 5 characters@mass.Maybe that’s what you’re doing wrong. What if you try
@massis the list of lines. Each line has words or just letters, separated by space.What that last line does is maps each line with
split /\s+/– which will split eachline like
'ba ab a G'into a list like('ba', 'ab', 'a', 'G')and@arraywillbecome a single list of words/letters.
Then it’s a matter of how you want to sort them. See the other answer as well.
Oh, and remember to put back the spaces when you write out your file:
If you want each line to be sorted interdependently of the other, that’s easy too:
That reads, ‘for every line in
@mass, split on space, sort and join back again with space’, and with the resulting array, join withnewlineto produce the output of the file.Note that you can drop in
sortwith a comparator likesort { $a cmp $b }etc.If your file is too big, then looping is maybe prudent: