1

嗨,我有一个看起来像的数组

@array = ( "city: chicago", "city: Newyork", "city: london", "country: india", "country: england", "country: USA")

我希望数组看起来像:

@array = ("city:", "chichago","Newyork","london","country:","india","england","USA")

谁能帮我弄清楚如何将数组格式化为如下格式。

4

2 回答 2

3

用空格分割数组的每个元素,如果已经看到city:或字符串,它会跳过它们,否则将它们与城市或国家名称一起映射为新元素,country:

my @array = ("city: chicago", "city: Newyork", "city: london", "country: india", "country: england", "country: USA");
my %seenp;
@array = map {
  my ($k,$v) = split /\s+/, $_, 2;
  $seenp{$k}++ ? $v : ($k,$v);
}
@array;
于 2013-07-17T05:56:58.033 回答
1

为什么要把事情分开,然后把它们塞回一个难以使用的结构中。一旦你让他们分开,让他们分开。他们更容易以这种方式工作。

#!/usr/bin/env perl

use strict;
use warnings;

# --------------------------------------

use charnames qw( :full :short   );
use English   qw( -no_match_vars );  # Avoids regex performance penalty

use Data::Dumper;

# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;

# conditional compile DEBUGging statements
# See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html
use constant DEBUG => $ENV{DEBUG};

# --------------------------------------


my @array = ( "city: chicago", "city: Newyork", "city: london", "country: india", "country: england", "country: USA");
my %hash = ();
for my $item ( @array ){
  my ( $key, $value ) = split m{ \s+ }msx, $item;
  push @{ $hash{$key} }, $value;
}

print Dumper \%hash;
于 2013-07-17T12:26:18.413 回答