首页 > 解决方案 > 跳过数组和循环中的值并直接显示在输出中

问题描述

我想在 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 中解决这个问题吗?

标签: regexperl

解决方案


这似乎做你想做的事。请注意,“增值税”不在%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

推荐阅读