[英]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.