1

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.

0

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

If the array is my @array = ("city: chicago", "city: Newyork", "city: london", "country: india", "country: england germany", "country: USA california"); Here In this case it is printing only the 1st part i.e., wahtever it is there before the name (england germany ) here it is printing only england not "england germany".
That's how split works. To get "england germany" you'd have to change my ($k, $v) = split; to something like my ($k, $v) = split /\s+/, $_, 2;. This limits the split to produce only two groups.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.