Link to home
Start Free TrialLog in
Avatar of Tolgar
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:

my $Files = join("," flushAll(@fileList));

Open in new window


Thanks,

Avatar of wilcoxon
wilcoxon
Flag of United States of America image

I'm not sure what you're asking.  Provided flashAll returns a list, the code you have should (almost) do exactly what you seem to be asking.

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);
$Files="@fileList";
If you want to convert into a string with list items separated by spaces, use this.
$Files="@fileList";

Open in new window


If you want some other separator, you may set the special variable $" to that value.

 
#Example
$" = "\t";

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tolgar
Tolgar

ASKER

Hi,
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);

Open in new window


is equivalent to
$" = ',';
$Files = "@fileList";

Open in new window


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";