gpt4 book ai didi

perl - 如何使用Perl检查文件的扩展名?

转载 作者:行者123 更新时间:2023-12-04 08:57:17 25 4
gpt4 key购买 nike

在我的perl脚本中,有一个文件作为论据传递。该文件可以是.txt文件,也可以是包含.zip文件的.txt文件。

我想写看起来像这样的代码

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

关于perl - 如何使用Perl检查文件的扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com