Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

regex - Skip the values in array and loop and directly show in output

I want to display the Tax Description of different countries for my new website in Perl. Based on the respective countries from the API I use, I get all the Tax Description in Uppercase letters.

I do not want single words VAT or SGST in array. I want the words of only multiple tax description words in array. Instead it should directly show what’s in the $word

Following is the code:

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;
}

Here are the inputs and outputs:

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’

I want the output for single tax description words as:

1. Input: ‘SGST’

Output: ‘SGST’

2. Input: ‘VAT’

Output: ‘VAT’

Can anyone please help as to how to fix this in Perl?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems to do what you want. Note that "VAT" is not in the %ignore hash, but is still left untouched.

I've written it as a Perl test file, so it can be run using prove. But you should be able to reuse the transform() subroutine in your code.

#!/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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...