0

I have code like the following:

 my $player_2ubid = grep { $_->ubid eq "2ubid" } @{$room_members };
 my $player_3ubid = grep { $_->ubid eq "3ubid" } @{$room_members };
 # ....
 my $player_11ubid = grep { $_->ubid eq "11ubid" } @{$room_members };

To avoid repetition, I want to go for a loop

for my $i ( 2 .. 11 ){
my $player_.$i.ubid = grep { $_->ubid eq "$i.ubid" } @{$room_members };
}

However this produces syntax error:

Can't modify concatenation (.) or string in scalar assignment at ***.t line 100, near "};"

What am I doing wrong here?

4
  • "$i.ubid" -> $i."ubid" or "${i}ubid" Commented Sep 4, 2013 at 7:14
  • @KoVadim thanks. I am suspecting that $player_.$i.ubid may also be in trouble Commented Sep 4, 2013 at 7:20
  • 5
    I think, you should study word "array". Commented Sep 4, 2013 at 7:23
  • 1
    Variable names with a number at the end is a really good indication that your code is designed badly. This should be an array or a hash. Commented Sep 4, 2013 at 10:40

2 Answers 2

4

First you have to write $i."ubid" or "${i}ubid" instead of "$i.ubid".

And I'd use an hash like:

my %player_ubid;
for my $i ( 2 .. 4 ){
    $player_ubid{$i} = grep { $_->ubid eq $i."ubid" } @{$room_members };
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are declaring the variable in wrong way, you can use hash instead of it.

But if you want to achieve in similar fashion, do it in this way

for my $i ( 2 .. 11 ){
  my $var = "player_".$i."ubid";
  $$var = grep { $_->ubid eq $i."ubid" } @{$room_members };
}

$$ creates the variable of the value inside the variable, just like in php.

9 Comments

$$var will produce warnings when use strict, right? And, it is almost always a bad idea. But I understand you provided it as another way to solve the problem.
What will be the scope of the variables created this way?
If you use strict then it is not a good approach, because scope of those variable remain inside the loop and also strict will produce warings when we use $$.
To make this clear: strict has nothing against the $$var – but it forbids using the names of variables as references. Using names as references is a bad programming practice (see varnie's link), and (in Perl) can only create global variables, which have infinite scope.
@amon It is not true that only global variables can be created. Try my $var = 'Foo::foo';
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.