2013-07-17 74 views
1

您好我有一個數組,它看起來像格式化數組元素

@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; 
+0

非常感謝它的工作。 – perl4289

+0

如果數組是我@array =(「城市:芝加哥」,「城市:紐約」,「城市:倫敦」,「國家:印度」,「國家:英格蘭德國」,「國家:美國加州」);在這裏,在這種情況下,僅打印第1部分,即wahtever它是存在的名稱(英格蘭德國)這僅打印英格蘭並不是「英格蘭德」之前。 – perl4289

+0

這是split'如何'工作。要獲得 「德國英格蘭」 你不得不改變'我($ K,$ V)=分裂;'喜歡的東西'我($ K,$ V)=分裂/ \ s + /,$ _,2;' 。這限制了「分裂」只產生兩組。 – dms

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;