我撰寫了 Perl 腳本,該腳本將 linux 路徑作為用戶的輸入,直到某個目錄,并列印其中具有通用名稱的所有目錄,例如,如果用戶輸入在/user/images/mobile_photos/里面,我有一個以likemobile_photos開頭的目錄串列,每個目錄都在里面目錄中的影像質量就像檔案中的字串一樣。現在我需要在一個檔案中獲取這些目錄的串列,其中包含目錄名稱旁邊的影像質量。image_image_user_1,image_user_2,...,image_user_10best,good,badquality.txt
一個例子的實際路徑
/user/images/mobile_photos/image_user_1/quality.txt
用戶應輸入為
/user/images/mobile_photos/
里面需要的輸出temp.txt是
image_user_1 good
image_user_2 bad
image_user_3 best
image_user_4 best
.
.
.
image_user_10 bad
以下是僅用于影像質量良好的代碼
#! /usr/bin/perl
use strict;
use warnings;
my $path = <STDIN>;
my $dir = system ("ls -d $path/image_*/quality.txt "good" > temp.txt");
print "$dir";
exit(0);
但我得到的終端輸出是空的/user/images/mobile_photos/。temp.txt
uj5u.com熱心網友回復:
更新 鑒于接受了(好的)答案,一些不清楚的(對我而言)似乎已解決,因此為了完整起見,我正在更新下面的代碼。(文字大體相同)
沒有理由為此出去system。那樣只會復雜得多,而且還有一個額外的挑戰是讓所有的引號和轉義符都正確
use warnings;
use strict;
use feature 'say';
use Path::Tiny; # path
use File::Spec::Functions qw(splitdir);
use File::Glob ':bsd_glob'; # glob
my $path = shift // die "Usage: $0 path\n";
my @dirs = grep { -d } glob "$path/image_*";
# Read sole word from a file in each dir, save list to file
my $out_file = 'temp.txt';
open my $fh_out, '>', $out_file or die "Can't open $out_file: $!";
foreach my $dir (@dirs) {
print $fh_out
(splitdir($dir))[-1],
' ',
path("$dir/quality.txt")->slurp; # has a linefeed
}
close $fh_out or warn "Error closing $out_file: $!";
內置的glob具有一小組元字符,如 shell 的。我使用File::Glob,它替換了 builtin glob,因為它還處理檔案名中的空格。我還使用方便的Path::Tiny來“啜飲”一個檔案(將其整個讀入一個字串),并使用File::Spec來獲取路徑的最后一部分,作為輸出的需要。
當然還有其他方法可以讀取目錄和選擇條目。
uj5u.com熱心網友回復:
使用低級opendir和readdir:
#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
chomp( my $path = <STDIN> );
opendir my $dir, $path or die "Can't open $path: $!";
while (my $dir = readdir $dir) {
next unless -d "$path/$dir" && $dir =~ /^image_/;
if (-f "$path/$dir/quality.txt") {
open my $q, '<', "$path/$dir/quality.txt"
or die "Can't open $dir/quality.txt: $!";
chomp( my $quality = <$q> );
say "$dir\t$quality";
} else {
warn "quality.txt not found in $dir.\n";
}
}
或使用Path::Tiny(強烈推薦!):
#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use Path::Tiny qw{ path };
chomp( my $path = <STDIN> );
$path = path($path);
die "Not a directory\n" unless $path->is_dir;
for my $dir ($path->children(qr/^image_/)) {
next unless $dir->is_dir;
my $quality_file = $dir->child('quality.txt');
if ($quality_file->is_file) {
chomp( my $quality = $quality_file->slurp );
say "$dir\t$quality";
} else {
warn "quality.txt not found in $dir.\n";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504241.html
上一篇:如何制作一個函式,該函式需要一個需要$a和$b但與perl中的呼叫者不同的包?
下一篇:Perltr替換但忽略前2個字符
