Tolgar
asked on
assign all elements of an array to a variable
Hi,
Is there a way to assign all elements of an array to a variable WITHOUT using a loop and then join them using a character like ","?
Something like:
Thanks,
Is there a way to assign all elements of an array to a variable WITHOUT using a loop and then join them using a character like ","?
Something like:
my $Files = join("," flushAll(@fileList));
Thanks,
$Files="@fileList";
If you want to convert into a string with list items separated by spaces, use this.
If you want some other separator, you may set the special variable $" to that value.
$Files="@fileList";
If you want some other separator, you may set the special variable $" to that value.
#Example
$" = "\t";
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi,
Thank you for all your replies. I am little puzzled so I want to make clear what I have understood:
This one:
is equivalent to
And they both get the elements of the array and concatenate them by using "," and assign it to a variable.
Am I right?
Thanks,
Thank you for all your replies. I am little puzzled so I want to make clear what I have understood:
This one:
my $Files = join(',', @fileList);
is equivalent to
$" = ',';
$Files = "@fileList";
And they both get the elements of the array and concatenate them by using "," and assign it to a variable.
Am I right?
Thanks,
Make a comma separated list of Array items.
True. However, when I wrote my response your second post wasn't up yet. Also, I prefer the simplicity of using join instead (single line, no special var to remember, and (should be) identical performance).
Yes, that is correct. Given:
@fileList = (qw(1 abc 23 14));
Both of those will result in
$Files = "1,abc,23,14";
@fileList = (qw(1 abc 23 14));
Both of those will result in
$Files = "1,abc,23,14";
You are missing a comma:
my $Files = join(",", flushAll(@fileList));
What is @fileList and what does flushAll do?
If you mean can you take the contents of files and assign it to a variable, then you can use File::Slurp.
my $Files = join(',', map { slurp($_) } @fileList);