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?
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.
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 (' ').
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.
$#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.
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. 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"> };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With