嗨,我有一个看起来像
的数组@array = ( "city: chicago", "city: Newyork", "city: london", "country: india", "country: england", "country: USA")
我希望数组看起来像:
@array = ("city:", "chichago","Newyork","london","country:","india","england","USA")
任何人都可以帮我解决如何将数组格式化为下面的格式。
答案 0 :(得分: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;
答案 1 :(得分: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;