programminglearner
programminglearner

Reputation: 542

Sorting with filehandle perl

I want to sort content by line for my output file.

I have this code

unless (open FILE1, '<'. $file1) {die "Couldn't open file\n";}
unless (open FILE2, '>'. $file2) {die "Couldn't open file\n";}

while (my $line = <FILE1>){
chomp $line;
print FILE2 sort (substr($line, 0, -1))."\n";

}

close FILE1;
close FILE2;

I would like to sort the lines in alphabetical order but it's not working. Without sort, I get desired output unsorted. How can I fix this so each line in my file output is sorted without having to do $sort -o $file $file.

Upvotes: 0

Views: 197

Answers (2)

drclaw
drclaw

Reputation: 2503

You could directly sort the output of <> in array context to remove a loop and make it a lot easier to read in my opinion.

If you are sorting lines, there is no need to chomp the end of line. If you leave it there then it cleans up the print statement by removing the manual newline character.

Also if you you lexical variables (eg my $input) instead of file handle (eg 'INPUT') for the open function, the file descriptors are automatically closed at the end of the scope.

use strict;
use warnings;

open my $input, "<", "input.txt";
open my $output, ">", "output.txt";

my @lines=sort <$input>;    #Use array context to read all lines in file


for (@lines) {
    print $output  $_;
}

Upvotes: 2

Adi Nistor
Adi Nistor

Reputation: 101

Easy is to read everything in an array. Sort the array. Then parse the array and process it however you want.

One easy-to-write solution for file reading is to use File::Slurper:

#!/usr/bin/perl
use strict;
use warnings;

use File::Slurper 'read_lines';
my $file1 = "a.a";
my $file2 = "b.b";

unless ( -f $file1 ) {die "Missing file: $file1\n";}

# Read all lines in an array
my @lines = read_lines($file1);
# Sort the array
my @sorted_lines = sort(@lines);


unless (open FILE2, '>'. $file2) {die "Couldn't open file\n";}
# Parse the sorted array
foreach my $line (@sorted_lines)
{
    # prcoess each line however you want
    print FILE2 substr($line, 0, -1)."\n";
}

close FILE2;

Upvotes: 0

Related Questions