2013-07-17 1 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

배열이 my @array = ("city : chicago", "city : Newyork", "city : london", "country : 인도", "country : 잉글랜드 germany", "country : USA california")입니다. 여기에서는 첫 번째 부분 만 인쇄합니다. 즉, 이름 앞에 (england germany) 여기에 "england germany"가 아닌 영국 만 인쇄하고 있습니다. – perl4289

+0

그건 어떻게 '분할'작동하는지. "england germany"를 얻으려면'my ($ k, $ v) = split;을'my ($ k, $ v) = split/\ s +/$ _, 2;와 같이 변경해야합니다. . 이것은 'split'이 두 그룹 만 생성하도록 제한합니다. – 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;