views:

690

answers:

4

I want to output the elements of an array in a specific format in Perl.

@myArray = ("A", "B", "C");
$text = something;

Something should be the string '"A" "B" "C"' (each element enclosed in double quotes).

However, if @myArray is empty, then $text should be too. I thought of using join(), such as

$text = "\"" . join("\" \"", @myArray) . "\"";
if ($text eq "\"\"")
{
    $text = "";
}

Which I think would work. However, is there a more elegant way to do this?

+12  A: 

Use map:

#!/usr/bin/perl

use strict;
use warnings;

my @a    = qw/ A B C /;
my @b;
my $text = join ' ', map { qq/"$_"/ } @a;
print "text for (@a) is [$text]\n";

$text = join ' ', map { qq/"$_"/ } @b;
print "text for (@b) is [$text]\n";

Also, to make the code cleaner, you can use the qq// operator (behaves exactly like "", but you can chose your delimiter) to avoid having escape the "s.

Chas. Owens
I'm a big fan of map. It's incredibly useful and I think every programmer should learn how to use it.
Jeremy Wall
map and reduce (from List::Util) are vital higher order functions. If you like map, you will love Higher Order Perl by Mark Jason Dominus: http://hop.perl.plover.com/
Chas. Owens
A: 

It might not do exactly what you're asking, but I'm a big fan of Data::Dumper for this sort of thing.

Paul Tomblin
+4  A: 

Chas. has the right answer, but sometimes I use the $" variable, which holds the string to put between array elements for interpolation:

my $text = do { local $" = q<" ">; qq<"@array"> };
brian d foy
+1  A: 

I am not sure about using a "join". Do you want a single scalar string with quoted elements or do you just want an array with quoted elements? If the latter then I suspect the following would do it

my @a = qw|a b c|;
@a = map {qq|"$_"|} @a;

Of course this sidesteps the test whether the elements were quoted originally. If you want the array elements quoted for inserting into a database using DBI for example, then the more appropriate way could be:

@a = map{$dbh->quote($_)} @a;

I hope this helps

Gurunandan
Why are you concatenating instead of interpolating? Good advice on the second bit though, I had assumed this was for output not passing to something else that would interpret the values as strings.
Chas. Owens
DOH! Of course. :) Change the second line of my first fragment to: @a = map {qq|"$_"|} @a;
Gurunandan