繁体   English   中英

用filehandle perl排序

[英]Sorting with filehandle perl

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

我有这个代码

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;

我想按字母顺序对行进行排序,但是它不起作用。 没有排序,我得到的期望输出未排序。 如何解决此问题,以便对文件输出中的每一行进行排序,而无需执行$sort -o $file $file

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

如果要对行进行排序,则无需删节行尾。 如果将其保留在此处,则它将通过删除手动换行符来清理print语句。

同样,如果您为open函数使用词法变量(例如, 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  $_;
}

轻松读取数组中的所有内容。 对数组进行排序。 然后解析数组并根据需要对其进行处理。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM