【问题标题】:Is there a better way to remove a string for an array of strings in perl?有没有更好的方法来删除 perl 中字符串数组的字符串?
【发布时间】:2012-12-04 23:44:28
【问题描述】:

我有一个 Perl 的 URL 数组,它们都包含“http://”。我想从每个字符串中删除该字符串,只留下域。我正在使用以下for 循环:

#!/usr/bin/perl

### Load a test array
my @test_array = qw (http://example.com http://example.net http://example.org);

### Do the removal
for (my $i=0; $i<=$#test_array; $i++) {
    ($test_array[$i] = $test_array[$i]) =~ s{http://}{};
}

### Show the updates
print join(" ", @test_array);

### Output: 
### example.com example.net example.org

它工作正常,但我想知道是否有更有效的方法(无论是在处理方面还是在减少打字方面)。有没有更好的方法从字符串数组中删除给定的字符串?

【问题讨论】:

    标签: regex arrays perl


    【解决方案1】:

    当我解析 uris 时,我使用URI

    use URI qw( );
    my @urls = qw( http://example.com:80/ ... );
    my @hosts = map { URI->new($_)->host } @urls;
    print "@hosts\n";
    

    【讨论】:

    • 这非常适合我概述的具体案例。我只是用它作为一个例子,我真的在寻找处理数组中字符串的通用方法。我应该在问题中更清楚地说明这一点。
    【解决方案2】:

    你不需要这行的赋值:

    ($test_array[$i] = $test_array[$i]) =~ s{http://}{};
    

    你可以使用:

    $test_array[$i] =~ s{http://}{};
    

    为了减少打字,利用$_ 变量:

    for (@test_array) {
      s{http://}{};
    }
    

    【讨论】:

    • 选择这个是因为它展示了如何处理一般的字符串。对于需要删除“http://”作为示例案例的内容,ikegami 的答案也值得一试。
    【解决方案3】:

    我建议使用map 函数。它将动作应用于数组中的每个元素。您可以将 for 循环压缩为一行:

    map s{http://}{}, @test_array;
    

    另外,附带说明一下,以空格分隔的格式打印数组内容的更简单方法是将数组放在双引号字符串中:

    print "@test_array";
    

    【讨论】:

    • 大多数人对使用 map 作为主题词感到畏惧。首选s{http://}{} for @test_array;
    • map 旨在用作列表运算符。它将一个列表映射到另一个列表——因此得名。使用它与普通的for相比没有任何优势,避免了滥用映射的概念,并且代码更清晰。
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多