|
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"
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. | [reply] [d/l] [select] |
|
|
$string = $q->param("us1"); # this is what entered +book +dog +cat
print join(',', $string), "\n";
# Output
"+book", "+dog", "+cat"
| [reply] [d/l] [select] |
|
|
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. | [reply] [d/l] [select] |
|
|
|
|
| |
|
|
Re: joining string content
by johngg (Canon) on Jun 24, 2025 at 09:55 UTC
|
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.
| [reply] [d/l] |
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]
| [reply] [d/l] [select] |
|
|
| [reply] |
|
|
print join ', ', map qq/"$_"/, split ' ', $str;
| [reply] [d/l] |
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?
| [reply] |
|
|