gpt4 book ai didi

linux - 检查平衡字符不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:40:49 24 4
gpt4 key购买 nike

我想编写一个 perl 脚本来检查字符串中的某些字符是否平衡。如果它们不平衡,它将删除它们。例如,如果一个字符串只包含左括号,则必须删除此字符。我使用了以下代码,但它不起作用...

sub checkBalance{
my $text= $_[0];
### Check Balanced Quates
my $count = ($text =~ tr/"//);
if ( $count%2 !=0)
{
$text=~ s/"//g;
}
### Check Balanced «»
if (((($text =~ m#(.*».*)#) && !($text =~ m#(.*«.*)#)) || !(($text =~ m#(.*».*)#) && ($text =~ m#(.*«.*)#))) || (index($text, "«")>index($text, "»")))
{
$text=~ s/»//g;
$text=~ s/«//g;
}
return $text;
}

为什么它不起作用?

pl文件是UTF8。样本输入是:

 می گوید: «یکی از اصول

预期的输出是:

 می گوید: یکی از اصول

我在英文字符串上使用了这段代码,它似乎适用于英文字符串,但不适用于其他语言,例如阿拉伯语和波斯语。

最佳答案

添加缺失的位:

use utf8;                               # Tell Perl script is encoded using UTF-8.
use strict;
use warnings;
use open ':std', ':encoding(UTF-8)'; # Tell Perl terminal expects UTF-8.
use feature qw( say );

sub checkBalance{
...
}

my $in = " می گوید: «یکی از اصول";
my $expect = " می گوید: یکی از اصول";
my $got = checkBalance($in);

say $in;
say $expect;
say $got;
say $got eq $expect ? "Got expected output" : "Didn't get expected output.";

我得到了正确的输出:

$ perl x.pl
می گوید: «یکی از اصول
می گوید: یکی از اصول
می گوید: یکی از اصول
Got expected output

我怀疑您没有告诉 Perl 您的源文件是使用 UTF-8 编码的。添加使用utf8;

以后请提供问题演示。简单地发布您的函数并不能说明问题。

关于linux - 检查平衡字符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com