Day 10. Dealing with Config::General's inability to provide single item arrays.

Today's recipe is very quick and simple, but scratches a minor irritation. Config::General (Apache-style), the default configuration file format for Catalyst, is great for readability, and the ease with which non-programmers can modify it. However, it doesn't deal with single item arrays well. That is, suppose you have the following configuration:

 <some_values>
 want_an_array some data
 </some_values>

But this will come out as a scalar:

 print $c->{config}->{some_values}

results in the output some data .

One way of fixing this is to just provide spurious extra keys in the config file:

 <some_values>
 want_an_array some data
 want_an_array junk
 </some_values>

And now you have an array:

 print $c->{config}->{some_values}
 ARRAY(0x800d80)

When it absolutely has to be an array and needs to be able to have a length of 1.

Unfortunately this is not entirely satisfactory, as sometimes you're using a plugin that requires an arrayref even with only one item (and subsequent entries can't be bogus without leading to problems), or if you need to know the length of the array without cumbersome workarounds. Enter Moose:

 sub setup {
     use Moose::Autobox;
     $_[0]->config->{some_values}{want_an_array} = [ $_[0]->config->{some_values}{want_an_array}->flatten ];
     shift->next::method(@_);
 }

Place this solution in MyApp.pm (it's just a normal subroutine with some Moose style syntax around it), and the problem is fixed!

ACKNOWLEDGEMENTS

Matt Trout (for the code), Jesse Sheidlower (for getting the code out of Matt finally)

AUTHOR

Kieren Diment <zarquon@cpan.org>