簡體   English   中英

如何使用 Perl 從路徑中提取文件名?

[英]How can I extract a filename from a path using Perl?

我有一個從數據庫填充的 Perl 變量。 它的名字是$path 我需要獲取另一個變量$file ,它只有來自路徑名的文件名。

我試過了:

$file = $path =~ s/.*\///;

我對 Perl 很陌生。

為什么要重新發明輪子? 使用File::Basename模塊:

use File::Basename;
...
$file = basename($path);

為什么$file=$path=~s/.*\\///; 不工作?

=~ 優先級高於=

所以

$file = $path =~s/.*\///;

被視為:

$file = ($path =~s/.*\///);

它在$path中進行替換並分配1 (如果發生替換)或'' (如果沒有發生替換)。

你想要的是:

($file = $path) =~s/.*\///;

它將$path的值分配給$file ,然后在$path中進行替換。

但是這個解決方案也有很多問題:

  1. 這是不正確的。 基於 Unix 的系統(不確定 Windows)中的文件名可以包含換行符。 但是. 默認情況下不匹配換行符。 因此,您必須使用s修飾符,以便. 也匹配換行符:

     ($file = $path) =~s/.*\\///s;
  2. 最重要的是,它不可移植,因為它假設/是路徑分隔符,這在某些平台(如 Windows(使用\\ )、Mac(使用: )時並非如此)。 因此,使用該模塊並讓它為您處理所有這些問題。

use File::Basename 

查看以下鏈接以獲取有關其工作原理的詳細說明:

http://p3rl.org/File::Basename

我認為最好的方法是——

use File::Basename;

my $file_name = basename($0);

所以變量$file_name將具有您的腳本的名稱

Path::Class 一開始可能看起來有點矯枉過正——制作文件和目錄路徑的對象——但它確實可以在復雜的腳本中得到回報,並提供很多好處,當你被范圍蔓延退回到角落時,它會防止出現意大利面。 File::Spec在第一個示例中用於解決路徑的樂趣。

use warnings;
use strict;
use Path::Class qw( file );
use File::Spec;

# Get the name of the current script with the procedural interface-
my $self_file = file( File::Spec->rel2abs(__FILE__) );
print
    " Full path: $self_file", $/,
    "Parent dir: ", $self_file->parent, $/,
    " Just name: ", $self_file->basename, $/;

# OO                                    
my $other = Path::Class::File->new("/tmp/some.weird/path-.unk#");
print "Other file: ", $other->basename, $/;
$url=~/\/([^\/]+)$/;
print "Filename $1\n";

就這么簡單:

$path =~ /.*[\/\\](.*)/;    # will return 1 (or 0) and set $1
my $file = $1;              # $1 contains the filename

要檢查文件名是否可用,請使用:

$file = $1 if $path =~ /.*[\/\\](.*)/;

圖案:

.*[\/\\](.*)
| |     |
| |     \- at last there is a group with the filename
| \------- it's the last / in linux or the last \ in windows
\--------- .* is very greedy, so it takes all it could

使用例如 https://regex101.com/ 來檢查正則表達式。

從路徑中提取文件名對於 Unix 和 Windows 文件系統都非常容易,無需任何包:

my $path;
$path = 'C:\A\BB\C\windows_fs.txt';     # Windows
#$path = '/a/bb/ccc/ddd/unix_fs.txt';    # Unix

my $file =  (split( /\/|\\/, $path))[-1];
print "File: $file\n";

# variable $file is "windows_fs.txt"  for Windows
# variable $file is "unix_fs.txt"     for Unix

邏輯非常簡單:創建一個包含路徑的所有元素的數組並檢索最后一個。 Perl 允許使用從數組末尾開始的負索引。 索引“-1”對應於最后一個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM