Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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

by boom (Scribe)
on Apr 18, 2009 at 13:09 UTC ( [id://758457]=perlquestion: print w/replies, xml ) Need Help??

boom has asked for the wisdom of the Perl Monks concerning the following question:

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

my @Array = ("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("\" \"", @Array) . "\"";
if ($text eq "\"\"")
{ $text = "";
}

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

  • Comment on How do I output each Perl array element sourrounded in quotes?

Replies are listed 'Best First'.
Re: How do I output each Perl array element sourrounded in quotes?
by AnomalousMonk (Archbishop) on Apr 18, 2009 at 21:05 UTC
    Which I think would work.
    Why think? Why not just try it?
    >perl -wMstrict -le "my @Array = ('A', 'B', 'C'); my $text = '\"' . join('\" \"', @Array) . '\"'; if ($text eq '\"\"') { $text = ''; } print $text; " "A" "B" "C"
    (However, heed the comments of other monks concerning handling of empty strings, etc.)
Re: How do I output each Perl array element sourrounded in quotes?
by Anonymous Monk on Apr 18, 2009 at 13:20 UTC
    #!/usr/bin/perl -- use strict; use warnings; my @Array = ("A", "B", "C"); my $text; if(@Array){ $text = join ' ', map { qq!"$_"! } @Array; } warn $text; $text = @Array ? join ' ', map { qq!"$_"! } @Array : ''; die $text; __END__ "A" "B" "C" at - line 12. "A" "B" "C" at - line 16.

      Or even simply (without extra testing for the emptiness of the array — if it's empty, join will join nothing):

      $text = join ' ', map qq("$_"), @Array;
        Your solution adds double quotes around the empty elements.

        Try this:

        print join ' ', map {qq("$_")} grep{$_} ('a', 'b', '', 'd', '', 'f');

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://758457]
Approved by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2024-04-20 04:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found