Austin Burke
Austin Burke

Reputation: 148

Convert comma separated values to key value pair Perl

I have an array of states in the format

('AL','Alabama','AK','Alaska','AR','Arkansas'...)

which I want formatted like:

[{'AL' => 'Alabama'},...]

This is primarily so that I can more easily loop through using the HTML::Template module (https://metacpan.org/pod/HTML::Template#TMPL_LOOP)

I'm fairly new to perl, so unsure about how to do this sort of action and can't find something similar enough.

Upvotes: 0

Views: 186

Answers (5)

ikegami
ikegami

Reputation: 386361

Wouldn't the following make more sense for HTML::Template?

states => [ { id => 'AL', name => 'Alabama' }, ... ]

This would allow you to use the following template:

<TMPL_LOOP NAME=states>
   <TMPL_VAR NAME=name> (<TMPL_VAR NAME=id>)
</TMPL_LOOP>

To achieve that, you can use the following:

use List::Util 1.29 qw( pairmap );

states => [ pairmap { +{ id => $a, name => $b } } @states ]

That said, you're probably generating HTML.

<select name="state">
   <TMPL_LOOP NAME=states>
      <option value="<TMPL_VAR NAME=id_html>"><TMPL_VAR NAME=name_html></option>
   </TMPL_LOOP>
</select>

To achieve that, you can use the following:

use List::Util 1.29 qw( pairmap );

{
   my %escapes = (
      '&' => '&amp;',
      '<' => '&lt;',
      '>' => '&gt;',
      '"' => '&quot;',
      "'" => '&#39;',
   );

   sub text_to_html(_) { $_[0] =~ s/([&<>"'])/$escapes{$1}/rg }
}

states => [ pairmap { +{ id_html => $a, name_html => $b } } map text_to_html, @states ]

Upvotes: 2

stevesliva
stevesliva

Reputation: 5665

map solution with a few perlish things

my @states = ('AL','Alabama','AK','Alaska','AR','Arkansas','VT','Vermont');

my %states;
map { $states{$states[$_]} = $states[$_+1] unless $_%2 } 0..$#states;

Upvotes: 0

Grinnz
Grinnz

Reputation: 9231

bundle_by from List::UtilsBy can easily create this format:

use strict;
use warnings;
use List::UtilsBy 'bundle_by';
my @states = ('AL', 'Alabama', 'AK', 'Alaska', 'AR', 'Arkansas', ... );
my @hashes = bundle_by { +{@_} } 2, @states;

Upvotes: 1

ysth
ysth

Reputation: 98398

use List::Util 1.29;
@state_hashes = List::Util::pairmap { +{ $a => $b } } @states;

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61520

Unless you need to keep this hash around for later use I think that simply looping through the elements two at a time would be simpler. You can accomplish this type of looping easily with splice:

my @states = ('AL','Alabama','AK','Alaska','AR','Arkansas'...);
while (my ($code, $name) = splice(@states, 0, 2)) {
   # operations here
}

Alternatively, you can use this same approach to create the data structure you want:

my @states = ('AL','Alabama','AK','Alaska','AR','Arkansas'...);
my @state_hashes = ();
while (my ($code, $name) = splice(@states, 0, 2)) {
   push @state_hashes, { $code => $name };
}
# do w/e you want with @state_hashes

Note: splice will remove elements from @states

Upvotes: 1

Related Questions