如何在 Perl 中拆分字符串
How to split string in Perl
我有一个包含路径的变量。
my $path = '../images/abc.png';
我想把它分成两条路径,这样:
my $directory = '../images';
my $FileName = 'abc.png';
怎么做?
只需根据最后一个正斜杠字符拆分您的输入即可。
my $line = "../images/abc.png";
my @abc = split /\/(?=[^\/]*$)/, $line;
print "Directory :\t" .$abc[0]."\n";
print "FileName :\t" .$abc[1]."\n";
输出:
Directory : ../images
FileName : abc.png
你最好使用核心模块File::Basename
#!/usr/bin/perl
use Modern::Perl;
use File::Basename;
my $path = '../images/abc.png';
my($filename, $dirs) = fileparse($path);
say $dirs,"\t",$filename
输出:
../images/ abc.png
你可以只使用正则表达式
use strict;
use warnings;
use 5.010;
my $path = '../images/abc.png';
my ($dir, $file) = $path =~ m|(.+)/(.*)|;
say for $dir, $file;
输出
../images
abc.png
我有一个包含路径的变量。
my $path = '../images/abc.png';
我想把它分成两条路径,这样:
my $directory = '../images';
my $FileName = 'abc.png';
怎么做?
只需根据最后一个正斜杠字符拆分您的输入即可。
my $line = "../images/abc.png";
my @abc = split /\/(?=[^\/]*$)/, $line;
print "Directory :\t" .$abc[0]."\n";
print "FileName :\t" .$abc[1]."\n";
输出:
Directory : ../images
FileName : abc.png
你最好使用核心模块File::Basename
#!/usr/bin/perl
use Modern::Perl;
use File::Basename;
my $path = '../images/abc.png';
my($filename, $dirs) = fileparse($path);
say $dirs,"\t",$filename
输出:
../images/ abc.png
你可以只使用正则表达式
use strict;
use warnings;
use 5.010;
my $path = '../images/abc.png';
my ($dir, $file) = $path =~ m|(.+)/(.*)|;
say for $dir, $file;
输出
../images
abc.png