来自url或文件补丁的perl获取图像和扩展名

时间:2012-01-15 02:23:22

标签: perl

我正在尝试使用向前或向后斜杠指定的URL或本地路径获取图像的名称和扩展名

输入可能是 http://test.com/hi23.gif 要么 /local/test/hi23.gif 要么 C:\测试\ 323.gif 要么 文件:\ BLA \ 3235.gif

#input: filename (i.e: http://test.com/hi4324.gif)
sub getFileName
{
  my $input = shift;  
  (my $filename = $input)  =~ m/(\w+\.(jpg|png|gif|jpeg)$)/i;  
  return $filename;
}

#input: filename (i.e: hi4324.gif)
sub getExtension
{
  my $input = shift;  
  (my $extension = $input)  =~ m/\w+\.(jpg|png|gif|jpeg)$/i;  
  return $extension;
}

3 个答案:

答案 0 :(得分:2)

如果您知道您的输入始终以/filename.ext结尾,那么请使用简单的正则表达式:

# $url has your url already
$url =~ /.*\/(.*?)\.(.*)/;
my ($filename, $ext) = ($1,$2);

但是如果查询字符串或其他各种格式可能更复杂,那么开始引入模块会容易得多。变量太多了。在使用文件系统时,我总是发现File::Basename最适合用于此目的。但我认为这不适用于URL。主URI模块看起来似乎已经足够了。 URI::SplitAPR::URI可以提供更多灵活性。

答案 1 :(得分:0)

use strict;
use warnings;
use File::Basename;
my @input = qw( http://test.com/hi23.gif  /local/test/hi23.gif  C:\test\323.gif file:\bla\3235.gif);

foreach my $some(@input){ 
$some =~ s!\\!/!g;          
my $basename = basename( $some);

if($basename =~ m/(.*)\.(.*)/){
my ($image_name,$image_extension) = ($1,$2);
print "\nInput is $some\nImage name is = $image_name, and extension is   $image_extension";
};
}

OUTPUT

Input is http://test.com/hi23.gif
Image name is = hi23, and extension is gif
Input is /local/test/hi23.gif
Image name is = hi23, and extension is gif
Input is C:/test/323.gif
Image name is = 323, and extension is gif
Input is file:/bla/3235.gif
Image name is = 3235, and extension is gif

答案 2 :(得分:0)

返回整个文件名和扩展名的子程序怎么样?

sub getFileNameExt {
  my ($path) = @_;
  return $1, $2 if $path =~ m{([^\\/.]+([^\\/]*)$)};
}

for my $p (qw(
    http://test.com/hi23.gif
    /local/test/hi23.gif
    C:\test\323.gif
    file:\bla\3235.gif)) {

  printf "%s - %s\n", getFileNameExt($p);
}

<强>输出

hi23.gif - .gif
hi23.gif - .gif
323.gif - .gif
3235.gif - .gif