【问题标题】:Ignore spaces in string comparison with array忽略字符串与数组比较中的空格
【发布时间】:2013-12-31 06:28:18
【问题描述】:

我的数组将具有以下值

array values will be like 

    "hi hello",
    "what are",
    "do you",
    "see here"

如何找到数组有值"hihello"

我用下面的方法来检查这个。

if ( trim($value) ~~ @array)

因为数组有空间而值没有,所以它不给出真值。有没有没有循环的简单方法?

【问题讨论】:

    标签: perl


    【解决方案1】:

    你指的是哪个trim?自 5.18 起,智能匹配 ~~ operator 处于试验阶段。

    use List::Util qw(first);
    
    my @array = (
      "hi hello",
      "what are",
      "do you",
      "see here"
    );
    
    # similar to grep(), first() also aliases $_ to array elements so changes
    # to $_ directly affect array elements
    # print "found it\n" if first { tr| ||d; $_ eq "hihello" } @array;
    #
    # non destructive translation, but it requires perl 5.12
    # print "found it\n" if first { tr| ||dr eq "hihello" } @array;
    
    print "found it\n" if first {
      (my $s = $_) =~ tr| ||d;
      $s eq "hihello";
    } @array;
    

    【讨论】:

    • 有趣,不知道 List::Util 中的“第一”是什么
    • @Paul 它类似于 grep 但应该更快,因为它不会遍历所有列表元素。
    • any 来自 List::MoreUtils(以及最近发布的 List::Util)可能比 first 更好。例如,如果您正在搜索字符串 "0" 而不是 "hihello"
    • @tobyink eval.in/84377 List::MoreUtils 很棒,但不幸的是不是标准 perl 的一部分,例如 List::Util
    【解决方案2】:

    也许这会有所帮助:

    use strict;
    use warnings;
    use v5.12;
    
    my @array = ( "hi hello", "what are", "do you", "see here" );
    my $value = "hihello";
    
    print qq/"$value" /,
      ( grep s/\s+//gr eq $value, @array ) ? 'found' : 'not found';
    

    输出:

    "hihello" found
    

    替换中的 /r 修饰符(根据 v5.12+)返回修改后的字符串。但是,此解决方案不会像 mpapec 使用 List::Util qw(first) 的解决方案那样在找到时终止遍历整个列表。

    【讨论】:

      【解决方案3】:

      它不起作用,因为trim 只删除文本前后的空格,而不是中间的空格。

      如果你不喜欢for 循环,Perl 有grepmap 以及foreach。在内部我相信这些都是循环。

      通读 PC 上的一些 perl 教程和文档可能会很有用。如果你的电脑上没有,试试http://perldoc.perl.org/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多