【问题标题】:How to split and concatenate strings in Perl? [closed]如何在 Perl 中拆分和连接字符串? [关闭]
【发布时间】:2015-09-29 06:00:40
【问题描述】:

我试图分割路径

Y:/P18/4000/source/xyz.pl 

我需要除 Y:\ 之外的所有内容,然后与另一条路径连接

http:/aswee/5000/trunk

让我得到

http:/aswee/5000/trunk/P18/4000/source/xyz.pl

有人可以推荐吗?

【问题讨论】:

  • @new = split(/\//, $x);我的 $y = "http://aswee/5000/trunk"; $path = "$y $new[1] $new[2] $new[3] $new[4]";打印文件 "$path\n";
  • 附带说明,如果您需要有关特定功能的文档(在本例中为split),您可以使用perldoc 命令,如下所示:perldoc -f split
  • 一般来说,我们希望看到您已经为解决问题做出了一些努力,然后我们才给您答案。

标签: perl split


【解决方案1】:

与其使用split,不如考虑使用File::Spec——这是一种独立于平台的方法。

#!/usr/bin/env perl
use strict;
use warnings;

use File::Spec;

my $path     = 'Y:/P18/4000/source/xyz.pl';
my $add_this = 'http:/aswee/5000/trunk';

my ( $volume, $directories, $file ) = File::Spec->splitpath($path);

my $url = $add_this . $directories . $file;
print $url;

【讨论】:

    【解决方案2】:

    在您的示例中向split() 函数添加第三个参数将使事情变得更容易。以下是您如何使用它以及其他几种方式:

    my $path = 'Y:/P18/4000/source/xyz.pl';
    my $url_prefix = 'http:/aswee/5000/trunk';
    
    my $url;
    # split into 2 parts and use the second part
    my ($drive, $path_in_drive) = split(/\//, $path, 2);
    $url = "$url_prefix/$path_in_drive";
    # OR
    # replace the part till the first / with the URL prefix
    $url = ($path =~ s!^.*?/!$url_prefix/!r);
    # OR
    # extract the part from the third character
    $url = $url_prefix . substr($path, 2);
    

    【讨论】:

    • 这很好用....非常感谢您的解释:)
    【解决方案3】:

    使用spilt函数:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my $path = 'Y:/P18/4000/source/xyz.pl';
    my $otherPath = 'http:/aswee/5000/trunk';
    
    #split in 2 part from ':' and use second one
    my (undef, $splitted) = split(':', $path, 2);
    
    print $otherPath . $splitted, "\n";
    

    输出:

    http:/aswee/5000/trunk/P18/4000/source/xyz.pl
    

    【讨论】:

    • 我发现了另一种方法 my $path = "Y:/P18/4000/source/xyz.pl"; $url_prefix = "http://asvn/cs_fcs_3000_4000/trunk";我的 $find = "Y:"; $path =~ s/$find/$url_prefix/g;打印 "$path\n";
    猜你喜欢
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多