Alex Rivera | Logout

How do I output each Perl array element surrounded in quotes?

Asked 2009-04-11T00:09:04.907
9

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?

Edit
Report

2 Answers

30

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.

answered 2009-04-11T00:19:13.183
1

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

answered 2009-04-11T07:29:49.060

Your Answer