[英]How do I open a file whose full name is unknown with Perl?
我想知道是否有任何東西可以讓我做以下事情:
folder1 has files "readfile1" "f2" "fi5"
我唯一知道的是我需要讀取以readfile
開頭的文件,我不知道字符串readfile
后名稱中有什么。 另外,我知道目錄中沒有其他文件以readfile
開頭。
如何使用open
命令打開此文件?
謝謝。
glob可用於查找匹配某個字符串的文件:
my ($file) = glob 'readfile*';
open my $fh, '<', $file or die "can not open $file: $!";
正如工具所暗示的那樣,你可以將glob
用於簡單的情況。
my ($file) = glob 'readfile*';
如果找到正確文件的標准更復雜,只需閱讀整個目錄並使用Perl的全部功能將列表縮小到您需要的位置:
use strict;
use warnings;
use File::Slurp qw(read_dir);
my $dir = shift @ARGV;
my @files = read_dir($dir);
# Filter the list as needed.
@files = map { ... } @files;
您不一定需要導入來讀取目錄的內容 - perl有一些內置函數可以做到這一點:
opendir DIR, ".";
my ($file) = grep /readfile.*/, readdir(DIR);
open FILE, $file or die $!;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.