如何在 Perl 中比较两个字符串?

发布于 2024-07-29 09:05:32 字数 93 浏览 5 评论 0原文

如何在 Perl 中比较两个字符串?

我正在学习 Perl,我在 StackOverflow 上查找了这个基本问题,但没有找到好的答案,所以我想我会问。

How do I compare two strings in Perl?

I am learning Perl, I had this basic question looked it up here on StackOverflow and found no good answer so I thought I would ask.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

ヤ经典坏疍 2024-08-05 09:05:33

请参阅 perldoc perlop。 根据字符串的情况使用 ltgteqnecmp比较:

如果左侧参数按字符串方式等于右侧参数,则二进制 eq 返回 true。

如果左侧参数按字符串方式不等于右侧参数,则二进制 ne 返回 true。

二进制 cmp 返回 -1、0 或 1,具体取决于左侧参数是否小于、等于或大于右侧参数。

Binary ~~ 在其参数之间进行智能匹配。 ...

ltlegegtcmp 使用排序规则如果旧版使用语言环境(但不是 use locale ':not_characters')有效,则按当前语言环境指定的(排序)顺序。 请参阅 perllocale。 不要将它们与 Unicode 混合,而只能与旧的二进制编码混合。 标准 Unicode::Collat​​eUnicode::Collat​​e::Locale 模块为排序问题提供了更强大的解决方案。

See perldoc perlop. Use lt, gt, eq, ne, and cmp as appropriate for string comparisons:

Binary eq returns true if the left argument is stringwise equal to the right argument.

Binary ne returns true if the left argument is stringwise not equal to the right argument.

Binary cmp returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

Binary ~~ does a smartmatch between its arguments. ...

lt, le, ge, gt and cmp use the collation (sort) order specified by the current locale if a legacy use locale (but not use locale ':not_characters') is in effect. See perllocale. Do not mix these with Unicode, only with legacy binary encodings. The standard Unicode::Collate and Unicode::Collate::Locale modules offer much more powerful solutions to collation issues.

小矜持 2024-08-05 09:05:33
  • cmp 比较

    <前><代码>'a' cmp 'b' # -1
    'b' cmp 'a' # 1
    'a' cmp 'a' # 0

  • eq 等于

    'a' eq 'b' # 0 
      'b' eq 'a' # 0 
      'a' eq 'a' # 1 
      
  • ne 不等于

    <前><代码>'a' 和 'b' # 1
    'b' 和 'a' # 1
    '一个' '一个' # 0

  • lt 小于

    <前><代码>'a' lt 'b' # 1
    'b' lt 'a' # 0
    'a' lt 'a' # 0

  • le 小于或等于

    'a' le 'b' # 1 
      'b' 'a' # 0 
      'a' le 'a'#1 
      
  • gt 大于

    'a' gt 'b' # 0 
      'b' gt 'a' # 1 
      'a' gt 'a' # 0 
      
  • ge 大于或等于

    <前><代码>'a' ge 'b' # 0
    'b' ge 'a' # 1
    '一个' '一个' # 1

参阅perldoc perlop 了解更多信息。

(我稍微简化了一点,因为除了 cmp 之外的所有值都返回一个空字符串和一个数字零值而不是 0 的值,以及一个值既是字符串 '1' 又是数值 1。这些值与 Perl 中的布尔运算符始终得到的值相同。您实际上应该只使用 return。布尔或数字运算的值,在这种情况下差异并不重要)。

  • cmp Compare

    'a' cmp 'b' # -1
    'b' cmp 'a' #  1
    'a' cmp 'a' #  0
    
  • eq Equal to

    'a' eq  'b' #  0
    'b' eq  'a' #  0
    'a' eq  'a' #  1
    
  • ne Not-Equal to

    'a' ne  'b' #  1
    'b' ne  'a' #  1
    'a' ne  'a' #  0
    
  • lt Less than

    'a' lt  'b' #  1
    'b' lt  'a' #  0
    'a' lt  'a' #  0
    
  • le Less than or equal to

    'a' le  'b' #  1
    'b' le  'a' #  0
    'a' le  'a' #  1
    
  • gt Greater than

    'a' gt  'b' #  0
    'b' gt  'a' #  1
    'a' gt  'a' #  0
    
  • ge Greater than or equal to

    'a' ge  'b' #  0
    'b' ge  'a' #  1
    'a' ge  'a' #  1
    

See perldoc perlop for more information.

( I'm simplifying this a little bit as all but cmp return a value that is both an empty string, and a numerically zero value instead of 0, and a value that is both the string '1' and the numeric value 1. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )

久光 2024-08-05 09:05:33

除了 Sinan Ünür 全面列出的字符串比较运算符之外,Perl 5.10 还添加了智能匹配运算符。

智能匹配运算符根据两个项目的类型进行比较。 请参阅下面的图表了解 5.10 的行为(我相信此行为在 5.10.1 中略有变化):

perldoc perlsyn “智能匹配详解”

智能匹配的行为取决于其参数的类型。 它始终是可交换的,即 $a ~~ $b 的行为与 $b ~~ $a 相同。 行为由下表确定:无论顺序如何,应用的第一行都确定匹配行为。

 $a $b 匹配类型隐含匹配代码 
    ===== ===== ===================== ============= 
    (超载胜过一切) 

    代码[+] 代码[+] 引用相等 $a == $b    
    任意代码[+]标量子真值$b−>($a)    

    哈希 哈希哈希键相同 [排序键 %$a]~~[排序键 %$b] 
    哈希数组哈希切片存在 grep {exists $a−>{$_}} @$b 
    哈希正则表达式哈希键 grep grep /$b/,键 %$a 
    散列 任何散列条目存在 $a−>{$b} 

    数组 数组 数组是相同的[*] 
    数组 正则表达式 数组 grep grep /$b/, @$a 
    Array Num 数组包含数字 grep $_ == $b, @$a  
    数组 任何包含字符串 grep $_ eq $b, @$a 的数组  

    任何 undef undefined !define $a 
    任何正则表达式模式匹配 $a =~ /$b/  
    Code() Code() 结果相等 $a−>() eq $b−>() 
    任意 Code() 简单闭包真值 $b−>() # 忽略 $a 
    Num numish[!] 数值相等 $a == $b    
    任意 Str 字符串相等 $a eq $b    
    任意 Num 数值相等 $a == $b    

    任意 任意字符串相等 $a eq $b    

  + − 这必须是原型(如果存在)不是“”的代码引用 
  (带有“”原型的潜艇由下方的“Code()”条目处理)  
  * - 也就是说,每个元素与另一个元素中相同索引的元素匹配 
  大批。   如果发现循环引用,我们将回退到引用  
  平等。    
  !   − 实数或看起来像数字的字符串 
   
  

当然,“匹配代码”并不代表真正的匹配代码:它只是用来解释预期的含义。 与 grep 不同,智能匹配运算符会尽可能短路。

通过重载进行自定义匹配 您可以通过重载 ~~ 运算符来更改对象的匹配方式。 这胜过了通常的智能匹配语义。 请参阅重载

In addtion to Sinan Ünür comprehensive listing of string comparison operators, Perl 5.10 adds the smart match operator.

The smart match operator compares two items based on their type. See the chart below for the 5.10 behavior (I believe this behavior is changing slightly in 5.10.1):

perldoc perlsyn "Smart matching in detail":

The behaviour of a smart match depends on what type of thing its arguments are. It is always commutative, i.e. $a ~~ $b behaves the same as $b ~~ $a . The behaviour is determined by the following table: the first row that applies, in either order, determines the match behaviour.

  $a      $b        Type of Match Implied    Matching Code
  ======  =====     =====================    =============
  (overloading trumps everything)

  Code[+] Code[+]   referential equality     $a == $b   
  Any     Code[+]   scalar sub truth         $b−>($a)   

  Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]
  Hash    Array     hash slice existence     grep {exists $a−>{$_}} @$b
  Hash    Regex     hash key grep            grep /$b/, keys %$a
  Hash    Any       hash entry existence     exists $a−>{$b}

  Array   Array     arrays are identical[*]
  Array   Regex     array grep               grep /$b/, @$a
  Array   Num       array contains number    grep $_ == $b, @$a 
  Array   Any       array contains string    grep $_ eq $b, @$a 

  Any     undef     undefined                !defined $a
  Any     Regex     pattern match            $a =~ /$b/ 
  Code()  Code()    results are equal        $a−>() eq $b−>()
  Any     Code()    simple closure truth     $b−>() # ignoring $a
  Num     numish[!] numeric equality         $a == $b   
  Any     Str       string equality          $a eq $b   
  Any     Num       numeric equality         $a == $b   

  Any     Any       string equality          $a eq $b   

+ − this must be a code reference whose prototype (if present) is not ""
(subs with a "" prototype are dealt with by the 'Code()' entry lower down) 
* − that is, each element matches the element of same index in the other
array. If a circular reference is found, we fall back to referential 
equality.   
! − either a real number, or a string that looks like a number

The "matching code" doesn't represent the real matching code, of course: it's just there to explain the intended meaning. Unlike grep, the smart match operator will short-circuit whenever it can.

Custom matching via overloading
You can change the way that an object is matched by overloading the ~~ operator. This trumps the usual smart match semantics. See overload.

深海里的那抹蓝 2024-08-05 09:05:33

这个问题的明显潜台词是:

为什么不能只使用 == 来检查两个字符串是否相同?

Perl 对于文本和数字没有不同的数据类型。 它们都由类型 “标量” 表示。 换句话说,字符串数字if你就这样使用它们

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

由于语言无法区分文本和数字,因此我们不能简单地重载 == 运算符来对这两种情况执行正确的操作。 因此,Perl 提供了 eq 来将值与文本进行比较:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

简而言之:

  • Perl 没有专门用于文本字符串的数据类型,
  • 请使用 ==!=,将两个操作数作为数字进行比较
  • 使用 eqne,将两个操作数作为文本进行比较

还有许多其他函数和运算符可用于比较标量值,但了解这两种形式之间的区别是重要的第一步。

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

ゞ记忆︶ㄣ 2024-08-05 09:05:33
print "Matched!\n" if ($str1 eq $str2)

Perl 有单独的字符串比较和数字比较运算符来帮助语言中的松散类型。 您应该阅读 perlop 了解所有不同的运算符。

print "Matched!\n" if ($str1 eq $str2)

Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.

无声情话 2024-08-05 09:05:33

如果您想提取两个字符串之间的差异,可以使用 String::差异

And if you'd like to extract the differences between the two strings, you can use String::Diff.

难忘№最初的完美 2024-08-05 09:05:33

我来寻找一个解决方案,在 Perl 中我可以比较 A > > B或Z< AA。 这里没有任何东西对我来说可靠,所以我想出了自己的解决方案。 技巧是为每个字母分配一个数字,

例如,

A=1
B=2
C=3 and so on

然后当时间到了比较是否 A > 时。 B 你得到相应的数字并比较它们,在这种情况下 1 > B 2

这是工作 perl 代码。

# header
use warnings;
use strict;

#create a hash of letters
my %my_hash_lookup;
my $letter_counter=0;
foreach my $letters ('A'..'ZZ')
{
    #print "$letters \n";
    
    $letter_counter++;
    my $key = $letters;
    my $keyValue = $letter_counter;
    $my_hash_lookup{$key}=$keyValue;
}


my $size = keys %my_hash_lookup;
print "hash size: $size ...\n";

#get number value of string letters
        my $my_hash_value1 = $my_hash_lookup{"A"};
        my $my_hash_value2 = $my_hash_lookup{"B"};
        
        if  ( (defined $my_hash_value1) && (defined $my_hash_value2))
        {

            if ($my_hash_value1 == $my_hash_value2)
            {
                #equal
            }
            elsif ($my_hash_value1 > $my_hash_value2)
            {
                #greater than
                
            }
            elsif ($my_hash_value1 < $my_hash_value2)
            {
                #less than
            }
            
        }

I came looking for a solution where in perl I could compare if A > B or Z < AA. Nothing here worked reliably for me so I came up with my own solution. The tricks is to assign a number for each letter

For example

A=1
B=2
C=3 and so on

Then when time comes to compare if A > B you get the corresponding numbers and compare them in this case 1 > 2

Heres working perl code.

# header
use warnings;
use strict;

#create a hash of letters
my %my_hash_lookup;
my $letter_counter=0;
foreach my $letters ('A'..'ZZ')
{
    #print "$letters \n";
    
    $letter_counter++;
    my $key = $letters;
    my $keyValue = $letter_counter;
    $my_hash_lookup{$key}=$keyValue;
}


my $size = keys %my_hash_lookup;
print "hash size: $size ...\n";

#get number value of string letters
        my $my_hash_value1 = $my_hash_lookup{"A"};
        my $my_hash_value2 = $my_hash_lookup{"B"};
        
        if  ( (defined $my_hash_value1) && (defined $my_hash_value2))
        {

            if ($my_hash_value1 == $my_hash_value2)
            {
                #equal
            }
            elsif ($my_hash_value1 > $my_hash_value2)
            {
                #greater than
                
            }
            elsif ($my_hash_value1 < $my_hash_value2)
            {
                #less than
            }
            
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文