我如何使用Perl检查文件的扩展名? [英] How can I check the extension of a file using Perl?
问题描述
.txt
文件或 .zip
包含 .txt
file。 我想编写看起来像这样的代码
if($ file是zip){
解压缩$ file
$ file =〜s / zip $ / txt /;
$ / code>
检查扩展的一种方法是在<$ c $然后匹配数组中的最后一个结果(由split返回)。
有没有更好的方法?
您可以为此使用File :: Basename。 code>#!/ usr / bin / perl
use 5.010;
使用strict;
使用警告;
使用File :: Basename;
my @exts = qw(.txt .zip);
while(my $ file =< DATA>){
chomp $ file;
my($ name,$ dir,$ ext)= fileparse($ file,@exts); $(bt)b
给出($ ext){
当('.txt'){
说$文件是一个文本文件;
当('.zip'){
说$ file是一个zip文件;
}
默认{
说$文件是未知的文件类型;
$ b $ __DATA__
file.txt
file.zip
file.pl
运行这个命令:
$ ./files
file.txt是一个文本文件
file.zip是一个zip文件
file.pl是一个未知文件类型
To my perl script, a file is passed as an arguement. The file can be a .txt
file or a .zip
file containing the .txt
file.
I want to write code that looks something like this
if ($file is a zip) {
unzip $file
$file =~ s/zip$/txt/;
}
One way to check the extension is to do a split on .
and then match the last result in the array (returned by split).
Is there some better way?
You can use File::Basename for this.
#!/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
Running this gives:
$ ./files
file.txt is a text file
file.zip is a zip file
file.pl is an unknown file type
这篇关于我如何使用Perl检查文件的扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!