• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 389
  • Last Modified:

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,

0
Tolgar
Asked:
Tolgar
  • 4
  • 4
2 Solutions
 
wilcoxonCommented:
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);
0
 
farzanjCommented:
$Files="@fileList";
0
 
farzanjCommented:
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

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
wilcoxonCommented:
If you do mean just assign all values of an array to a variable, farzanj's response will do that (separated by spaces).

If that is what you're asking and you want commas, then this will work:

my $Files = join(',', @fileList);
0
 
farzanjCommented:
You can still create a comma separated list by doing my trick again

$" = ',';
$Files = "@fileList";

Open in new window

0
 
TolgarAuthor Commented:
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,
0
 
farzanjCommented:
Make a comma separated list of Array items.
0
 
wilcoxonCommented:
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).
0
 
wilcoxonCommented:
Yes, that is correct.  Given:

@fileList = (qw(1 abc 23 14));

Both of those will result in

$Files = "1,abc,23,14";
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now