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

How can i have an output like this

"+book", "+dog", "+cat"

from string values, i dont want to use array

my $string = (+book +dog +cat); print join(',', $string), "\n";

but my main target is to get what entered from html and join it like this

$string = $q->param("us1"); # this is what entered +book +dog +cat print join(',', $string), "\n";

output like this

"+book", "+dog", "+cat"

Replies are listed 'Best First'.
Re: joining string content
by Corion (Patriarch) on Jun 24, 2025 at 08:59 UTC

    Given your code, that's impossible.

    my $string = (+book +dog +cat);

    Given your code, Perl sees:

    my $string = 'book' + 'dog' + 'cat';

    ... which makes Perl calculate the sum of book, dog and cat, which is zero, because (non-number-looking) strings evaluate to 0 in Perl.

    Can you show us a complete, runnable example of the code and data you have that replicates your problem?

    I think you want something like Text::CSV_XS, if your goal is to produce a CSV file, for example for Excel.

      is this not also possible

      $string = $q->param("us1"); # this is what entered +book +dog +cat print join(',', $string), "\n";
      # Output "+book", "+dog", "+cat"

        Maybe the core of your problem is that you have a string like this:

        my $string = '+book +dog +cat';

        ... and you want to transform it into

        "+book", "+dog", "+cat"

        Then, the following code could do that:

        my $string = '+book +dog +cat'; my @raw_params = split /\s+/, $string; my @quoted_params = map { qq{"$_"} } @raw_params; my $quoted_params_string = join ", ", @quoted_params; print $quoted_params_string;

        Update: johngg++ spotted an error that resulted in pluses being added unnecessarily.

Re: joining string content
by johngg (Canon) on Jun 24, 2025 at 09:55 UTC

    No intermediate array here.

    johngg@aleatico:~$ perl -Mstrict -Mwarnings -E 'say q{}; my $str = q{+book +dog +cat}; say join q{, }, map { q{"} . $_ . q{"} } split m{\s+}, $str;' "+book", "+dog", "+cat"

    I hope this is helpful.

    Cheers,

    JohnGG

Re: joining string content
by choroba (Cardinal) on Jun 24, 2025 at 11:08 UTC
    A regex substitution can do that, but its readability is not high:
    my $str = '+book +dog +cat'; print '"', $str =~ s/ /", "/gr, '"';
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      Given OP's code, as an important criteria, readability is not high!

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re: joining string content
by hippo (Archbishop) on Jun 24, 2025 at 09:40 UTC
    i dont want to use array

    Why not? An array seems like precisely the right thing to use here.

    Update: Is this an XY Problem? What are you actually trying to do in the bigger picture?


    🦛