Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 502
rlbond Avatar asked Apr 11 '09 00:04

rlbond


People also ask

How do you access each element of an array in Perl?

To access a single element of a Perl array, use ($) sign before variable name. You can assume that $ sign represents singular value and @ sign represents plural values. Variable name will be followed by square brackets with index number inside it. Indexing will start with 0 from left side and with -1 from right side.

How do I insert a quote in Perl?

The String is defined by the user within a single quote (') or double quote (“). In Perl, strings can be put in between double-quotes (” “) or in between single-quotes (' ').

What does \@ mean in Perl?

the \@ notation will return a reference (or pointer) to the array provided, so: $arrayref = \@array. will make $arrayref a reference to @array - this is similar to using the *p pointer notation in C.

How do I print the number of elements in an array in Perl?

$#arr returns last index of array. indexing starting at 0, then is true equation $#arr+1 == @arr . If you write some element out of order, for example $arr[100]='any', then table is automatically increased to max index 100, and (including index 0) to 101 elements.


2 Answers

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.

like image 140
Chas. Owens Avatar answered Oct 12 '22 03:10

Chas. Owens


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"> };
like image 33
brian d foy Avatar answered Oct 12 '22 03:10

brian d foy