[英]how to combine directory path in perl
我有一個perl腳本,我在其中提供目錄作為輸入的路徑。 目錄中包含xml文件。
在我的代碼中,我遍歷所有xml文件並為所有xml文件創建絕對路徑。 代碼工作正常。
#!/usr/bin/perl
use File::Spec;
$num_args = $#ARGV + 1;
if ($num_args != 1) {
print "\nUsage: $0 <input directory>\n";
exit;
}
my $dirPath = $ARGV[0];
opendir(DIR, $dirPath);
my @docs = grep(/\.xml$/,readdir(DIR));
foreach my $file (@docs)
{
my $abs_path = join("",$dir,$file);
print "absolute path is $abs_path";
}
我在這里的問題是,加入$ dirPath和$ file沒有分隔符,這意味着$ dirPath必須以“/”結尾。 那么在perl中是否有任何方法或內置函數可以處理這種情況並替換join方法。
我想要的只是不用擔心分隔符“/”。 即使用路徑調用腳本為“/ test / dir_to_process”或“/ test / dir_to_process /”,我也應該能夠為所有存在的xml文件生成正確的絕對路徑,而不必擔心分隔符。
如果有人有任何建議,請告訴我。
答案在File :: Spec的文檔中,例如,catfile:
$path = File::Spec->catfile( @directories, $filename );
或catpath:
$full_path = File::Spec->catpath( $volume, $directory, $file );
請注意你給出的建議。 當忽略對以前帖子的評論和回答時,繼續提問是很荒謬的。
您必須始終在您編寫的每個 Perl程序的頂部use strict
並use warnings
,並使用my
聲明每個變量。 這並不難,如果您發布沒有這些措施的代碼,您將受到譴責。
您在程序中use
File::Spec
模塊但從不使用它。 使用File::Spec::Functions
通常更容易,它導出File::Spec
提供的方法,因此不需要使用面向對象的調用樣式。
catfile
將正確地將文件(或目錄)名稱連接到路徑,如果路徑分隔符不正確,則執行正確的操作。 這個重寫你的程序工作正常。
#!/usr/bin/perl
use strict;
use warnings;
use File::Spec::Functions 'catfile';
if (@ARGV != 1) {
print "\nUsage: $0 <input directory>\n";
exit;
}
my ($dir_path) = @ARGV;
my $xml_pattern = catfile($dir_path, '*.xml');
while ( my $xml_file = glob($xml_pattern) ) {
print "Absolute path is $xml_file\n";
}
如果不存在,這將添加尾部斜杠:
$dirPath =~ s!/*$!/!;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.