smintitule
smintitule

Reputation: 43

Is it possible to dynamically expand a scalar assignment depending on the size of an array?

So, here's the deal. I have an array, let's call it

@array = ('string1','string2','string3','string4');

etc., etc. I have no way of knowing how large the array is or what the contents are, specifically, except that it is an array of strings.

I also have a variable which needs to be changed depending on the size and contents of the array.

Here's a sample easy assignment of that variable, along with the array that would have generated the assignment:

@array = ('string1','string2','string3');

$var = Some::Obj1(Some::Obj2('string1'),
                 Some::Obj2('string2'), 
                 Some::Obj2('string3'));

Then, if for instance, I had the following @array,

@array = ('string1','string2','string3','string4','string5');

My assignment would need to look like this:

$var = Some::Obj1(Some::Obj2('string1'),
                 Some::Obj2('string2'), 
                 Some::Obj2('string3'), 
                 Some::Obj2('string4'), 
                 Some::Obj2('string5'));

Can you guys think of any way that something like this could be implemented?

Upvotes: 3

Views: 111

Answers (2)

Joseph Myers
Joseph Myers

Reputation: 6552

Yes, you just do

$var = Some::Obj1(map(Some::Obj2($_), @array));

That produces the exact same result as the code you wrote:

$var = Some::Obj1(Some::Obj2('string1'),
             Some::Obj2('string2'), 
             Some::Obj2('string3'), 
             Some::Obj2('string4'), 
             Some::Obj2('string5'));

Of course, it goes without saying that you should use either my or our before the variable as appropriate if you are initializing it for the first time. If you wish to perform more complicated operations using map, an entire block of code can be enclosed in braces and the comma omitted, i.e.,

map {operation 1; operation 2; ...; final operation stored as result;} @array

Upvotes: 1

TLP
TLP

Reputation: 67908

Well, if all you need is to turn some strings into a list of objects inside an object... Why not map?

my @array = ('string1','string2','string3','string4','string5');
my $var = Some::Obj1(map { Some::Obj2($_) } @array);

Upvotes: 10

Related Questions