使用filehandle perl进行排序

使用filehandle perl进行排序,perl,sorting,file-handling,Perl,Sorting,File Handling,我想为输出文件按行对内容进行排序 我有这个密码 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";

我想为输出文件按行对内容进行排序

我有这个密码

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;


除非(打开文件1),简单的方法是读取数组中的所有内容。对数组进行排序。然后解析数组并根据需要进行处理

一种易于编写的文件读取解决方案是使用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;

简单的方法是读取数组中的所有内容。对数组进行排序。然后解析数组,并根据需要进行处理

一种易于编写的文件读取解决方案是使用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;

在我看来,您可以直接在数组上下文中对
的输出进行排序,以删除循环并使其更易于阅读

如果要对行进行排序,则无需选择行尾。如果将行尾保留在那里,则会通过删除手动换行符来清除
print
语句

此外,如果为
打开
函数使用词法变量(例如
my$input
)而不是文件句柄(例如“input”),则文件描述符将在作用域的末尾自动关闭

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  $_;
}
使用严格;
使用警告;
打开我的$input“,”output.txt“;
my@lines=sort;#使用数组上下文读取文件中的所有行
对于(@行){
打印$output$;
}

您可以直接在数组上下文中对
的输出进行排序,以删除循环,并在我看来使其更易于阅读

如果要对行进行排序,则无需选择行尾。如果将行尾保留在那里,则会通过删除手动换行符来清除
print
语句

此外,如果为
打开
函数使用词法变量(例如
my$input
)而不是文件句柄(例如“input”),则文件描述符将在作用域的末尾自动关闭

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  $_;
}
使用严格;
使用警告;
打开我的$input“,”output.txt“;
my@lines=sort;#使用数组上下文读取文件中的所有行
对于(@行){
打印$output$;
}

@mosvy welp,成功了。谢谢!@mosvy welp,成功了。谢谢!