本文详细介绍perl中 路径获取模块:Cwd、FindBin和File::Basename的使用。
目录
欢迎微信随缘关注@pythonic生物人
1、FindBin
$Bin
$Script
2、Cwd
getcwd() cwd() fastcwd() fastgetcwd()
abs_path
3、File::Basename
1、FindBin
- $Bin
返回被执行的脚本绝对路径;
- $Script
返回被执行的脚本名称;
2、Cwd
- getcwd() cwd() fastcwd() fastgetcwd()
Cwd 模块默认载入以上四函数,返回执行脚本的路径;例如您在/home/test 下执行了perl hello.pl,则以上四函数均返回/home/test;
- abs_path
需要自己载入,即 use Cwd qw(abs_path);abs_path(
file例如,
#!/usr/bin/perl
use strict;
use warnings;
use FindBin qw($Bin $Script $RealBin $RealScript);
#use Cwd qw(abs_path);
use Cwd;
#默认导入函数 cwd(), getcwd(), fastcwd()及fastgetcwd()
use Cwd qw(abs_path);
print "$Binn";#$Bin 返回脚本的绝对路径
print "$Scriptn";#$Script返回脚本名字
print "$RealBinn";
print "$RealScriptn";
#getcwd() cwd() fastcwd() fastgetcwd() 获取当前"执行程序"的路径
my $dir = getcwd();
my $dir1 = cwd();
my $dir2 = fastcwd();
my $dir3 = fastgetcwd();
print "n";
print "$dirn";
print "$dir1n";
print "$dir2n";
print "$dir3n";
print "n";
my $abs_path = abs_path($Script);#返回$Script绝对路径/$Script
print "$abs_pathn";
cd /home/study/perl/#执行脚本的路径
perl test/findbin.pl
/home/study/perl/test#被执行脚本所在路径
findbin.pl
/home/study/perl/test
findbin.pl/home/study/perl/#返回执行脚本的路径
/home/study/perl/
/home/study/perl/
/home/study/perl/
/home/study/perl/findbin.pl#返回执行脚本的路径/被执行脚本
3、File::Basename
File::Basename模块拆分路径例如,path.pl
#! /usr/bin/perl
use strict;
use warnings;
use File::Basename;
my $path = $ARGV[0];
my($filename, $dirs, $suffix) = fileparse($path,qr/.[^.]*/);
#以上分别为文件名,文件绝对路径,文件后缀名
print"$filenamet$dirst$suffixn";
my $filename1=basename($path);#默认返回带后缀文件名
my $dirname1=dirname($path);#返回绝对路径
print "$filename1t$dirname1n";
perl path.pl /home/study/max.pl
max /home/study/ .pl
max.pl /home/study
参考资料
https://perldoc.perl.org/Cwd.html https://perldoc.perl.org/FindBin.htmlhttps://perldoc.perl.org/File/Basename.html
欢迎微信随缘关注@pythonic生物人