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

#!/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.
  • Comment on Re: How do I output each Perl array element sourrounded in quotes?
  • Download Code

Replies are listed 'Best First'.
Re^2: How do I output each Perl array element sourrounded in quotes?
by almut (Canon) on Apr 18, 2009 at 13:25 UTC

    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

        But grepping on  $_ filters out the string  '0' or a numeric value of 0.

        >perl -wMstrict -le "my @Array = ('A', undef, 'B', '0', 'C', 0); print join ' ', map {qq(\"$_\")} grep { $_ } @Array; " "A" "B" "C"
        Grepping on length will allow handling of  '0' or 0, but is unhappy with an undefined value (if this should be an issue).

        >perl -wMstrict -le "my @Array = ('A', undef, 'B', '0', 'C', 0); print join ' ', map {qq(\"$_\")} grep { length } @Array; " Use of uninitialized value in length at -e line 1. "A" "B" "0" "C" "0"
        Grepping on both defined and length handles a broad range of variations.
        >perl -wMstrict -le "my @Array = ('A', undef, 'B', '0', 'C', 0); print join ' ', map {qq(\"$_\")} grep {defined and length} @Array; " "A" "B" "0" "C" "0"