对于我的 Perl 脚本,一个文件作为参数传递。该文件可以是.txt
文件或一个.zip
文件包含.txt
file.
我想编写看起来像这样的代码
if ($file is a zip) {
unzip $file
$file =~ s/zip$/txt/;
}
检查扩展的一种方法是进行拆分.
然后匹配数组中的最后一个结果(由 split 返回)。
有更好的办法吗?
您可以为此使用 File::Basename。
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use File::Basename;
my @exts = qw(.txt .zip);
while (my $file = <DATA>) {
chomp $file;
my ($name, $dir, $ext) = fileparse($file, @exts);
given ($ext) {
when ('.txt') {
say "$file is a text file";
}
when ('.zip') {
say "$file is a zip file";
}
default {
say "$file is an unknown file type";
}
}
}
__DATA__
file.txt
file.zip
file.pl
运行这个给出:
$ ./files
file.txt is a text file
file.zip is a zip file
file.pl is an unknown file type
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)