【问题标题】:Skip the values in array and loop and directly show in output跳过数组和循环中的值并直接显示在输出中
【发布时间】:2019-10-22 12:05:50
【问题描述】:

我想在 Perl 中为我的新网站显示不同国家的税务说明。根据我使用的 API 中的各个国家/地区,我得到了所有大写字母的税收说明。

我不希望数组中包含单个单词 VAT 或 SGST。我想要数组中只有多个税收描述词的词。相反,它应该直接显示 $word

中的内容

以下是代码:

sub maybe_ucfirst {
    my ($word) = @_;
    my %ignore = map { $_ => undef } qw(GST AZ);
    return exists $ignore{$word} ? $word : ucfirst Lc $word;
}

my @inputs = ('AUSTRALIA GST', 'AZ COUNTY TAX', 'NEW ZEALAND GST', 'VAT');
for my $s (@inputs) {
    $s =~ s/(\w+)/maybe_ucfirst($1)/eg;
    say $s;
}

这里是输入和输出:

1: Input: ‘AUSTRALIA GST’

Output: ‘Australia GST’


2. Input: ‘AZ COUNTY TAX’

Output: ‘AZ County Tax’


3. Input: ‘NEW ZEALAND GST’

Output: ‘New Zealand GST’


4. Input: ‘VAT’

Output: ‘Vat’


5. Input: ‘SGST’

Output: ‘Sgst’

我希望单个税收描述词的输出为:

1. Input: ‘SGST’

Output: ‘SGST’

2. Input: ‘VAT’

Output: ‘VAT’

任何人都可以帮助如何在 Perl 中解决这个问题吗?

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    这似乎可以满足您的需求。请注意,“增值税”不在 %ignore 哈希中,但仍保持不变。

    我已将它编写为 Perl 测试文件,因此可以使用 prove 运行它。但是您应该能够在代码中重用 transform() 子例程。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Test::More;
    
    while (<DATA>) {
      chomp;
    
      my ($input, $expected) = split /,/;
      is(transform($input), $expected);
    }
    
    done_testing();
    
    sub transform {
      my ($in) = @_;
    
      my %ignore = map { $_ => 1 } qw[GST AZ];
    
      my @in_array = split /\s+/, $in;
    
      # Do nothing if we have a single word
      return $in if @in_array == 1;
    
      return join ' ', map {
        $ignore{$_} ? $_ : ucfirst lc $_;
      } @in_array;
    }
    
    __DATA__
    AUSTRALIA GST,Australia GST
    AZ COUNTY TAX,AZ County Tax
    NEW ZEALAND GST,New Zealand GST
    VAT,VAT
    SGST,SGST
    

    【讨论】:

    • 感谢@Dave Cross
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2019-02-03
    • 2017-05-21
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多