regex - 跳过数组和循环中的值并直接显示在输出中
问题描述
我想在 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 中解决这个问题吗?
解决方案
这似乎做你想做的事。请注意,“增值税”不在%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
推荐阅读
- javascript - nativeElement select 等待绑定数据
- php - session_start() 在特定脚本上静默失败
- python - 如何在 AWS Lambda 中直接导入 Google 模块?
- c++ - 在 TCP 套接字上执行 async_read_some() 时出现 EOF...但是连接仍然存在
- ios - Flutter ios - 在模拟器上运行的应用程序无法部署到 iphone - 找不到 -lFirebaseCore 的库
- java - 我正在使用 Files.move 函数移动文件,但它不继承父文件夹权限
- javascript - 如何在本机反应中切换抽屉导航器?
- go - 如何在 Go on Google Cloud Functions 上使用子包?
- powershell - 无法将“System.String”转换为类型“WebServiceProxy.ExternalID”
- asp.net - ASP.NET CORE 2.1 FromRoute 和 FromBody 模型绑定