perl4289
perl4289

Reputation: 23

Formatting Array elements

Hi I have an Array which looks like

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

I want the array to look like:

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

Can anyone help me out how to format the array to look like the below format.

Upvotes: 1

Views: 97

Answers (2)

shawnhcorey
shawnhcorey

Reputation: 3601

Why separate things out and stuff them back into a hard to use structure. Once you get them separated, keep them separated. They're much easier to work with that way.

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

Upvotes: 1

mpapec
mpapec

Reputation: 50657

Splits every element of array by white spaces, and if city: or country: strings were already seen, it skips them, otherwise maps them as new elements together with city or country name,

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;

Upvotes: 3

Related Questions