Home > Archive > PERL Beginners > December 2004 > How to concatenate nested arrays of strings
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
How to concatenate nested arrays of strings
|
|
| Siegfried Heintze 2004-12-28, 3:55 am |
| I'm writing perl cgi and I like to buffer my output in an array of strings.
I just decided it would be very useful to be able to have nested arrays.
Below is a little function that does what a want. However,
(1) Is there a more compact way of performing this nested concatenation?
(2) Hasn't someone else already written a function like this that is
part of the standard repertoire?
(3) Assuming I have to use my own function below: My code only
concatenates the elements first argument. How can I concatenate all the
elements of all the function arguments?
(4) Is it possible to have nested lists? How would I modify my code to
handle those?
Thanks,
Siegfried
use strict;
use warnings;
sub concat {
my $sResult = shift;
return join("", map { ref($_) eq "ARRAY"? concat($_) :"$_ " }
@{$sResult});
}
print concat (["hello ", "there", ["a", "nested", "array"], "world!"]);
| |
| John W. Krahn 2004-12-28, 8:59 am |
| Siegfried Heintze wrote:
> I'm writing perl cgi and I like to buffer my output in an array of strings.
> I just decided it would be very useful to be able to have nested arrays.
>
> Below is a little function that does what a want. However,
>
> (1) Is there a more compact way of performing this nested concatenation?
>
> (2) Hasn't someone else already written a function like this that is
> part of the standard repertoire?
>
> (3) Assuming I have to use my own function below: My code only
> concatenates the elements first argument. How can I concatenate all the
> elements of all the function arguments?
>
> (4) Is it possible to have nested lists? How would I modify my code to
> handle those?
>
>
> use strict;
> use warnings;
>
> sub concat {
>
> my $sResult = shift;
>
> return join("", map { ref($_) eq "ARRAY"? concat($_) :"$_ " }
> @{$sResult});
>
> }
>
> print concat (["hello ", "there", ["a", "nested", "array"], "world!"]);
Is this what you want?
$ perl -le'
sub concat { return join " ", map ref eq "ARRAY" ? concat( @$_ ) : $_, @_ }
print concat( [ "hello ", "there", [ "a", "nested", "array" ], "world!" ] );
'
hello there a nested array world!
John
--
use Perl;
program
fulfillment
|
|
|
|
|