tags:

views:

72

answers:

2
@browser = ("NS", "IE", "Opera");

my $add_str = "Browser:";

$count = 0; 
foreach  (@browser) { 
 my $br = $_;
 $browser[$count] =  "$add_str:$br";
 $count++ ;

}

is there any other way to do this ? best way ?

+10  A: 

You could use map.

@browser = ("NS", "IE", "Opera");

my $add_str = "Browser";
@browser = map { "${add_str}:$_"; } @browser;
Pat
This has the minor problem that if `@browser` is very large, then you will eat more memory than you want to. Also, you only need the braces if there are two colons in a row (i.e. a package separator). One is ignored.
Chas. Owens
+7  A: 

In Perl 5, the for loop aliases each item, so you can simply say

#!/usr/bin/perl

use strict;
use warnings;

my @browsers = qw/NS IE Opera/;

my $add_str = "Browser:";

for my $browser (@browsers) {
    $browser = "$add_str:$browser";
}

print join(", ", @browsers), "\n";
Chas. Owens
Using the aliasing feature of the `for` harms readability. `map` is what everybody knows and uses.
Dummy00001
@Dummy00001 I disagree with you on all three points. The aliasing feature of `for` is very readable, not everyone knows what `map` is, and for something like this using a non-void `map` could be *very* unsuitable (if modifying a large list) and using a void `map` is less readable than the aliasing `for`.
Chas. Owens
map takes a list and returns a list. for(each) iterates a list and usually doesn't modify it. Not using the common idiom map seems like premature optimization to me. How big does the list have to be before the difference is noticable?
asjo
The `for` loop is also a common idiom. I wouldn't be surprised to see either in use. If I didn't know how many items would be in the list I would likely use the `for` loop for the same reason I use `while (<>)` instead of `for (<>)`. For a list of 10 items, `for` is twice as fast as `map` (but slower than a void `map`). With 10k items it is nearly three times as fast. You can run the [benchmark](http://codepad.org/lU3fifAP) yourself. But the real issue isn't speed (this is Perl after all), it is memory usage. The `map` requires twice the memory. With a large array that could be very painful.
Chas. Owens
If you’re trying to write C or PHP in Perl, maybe you won’t use the aliasing property of `foreach`. If you’re writing Perl, though, you should. It’s perfectly intentional that `foreach` aliases: that makes many cases easier to write. In this particular case, though, I agree that `map` is the more readable solution.
Aristotle Pagaltzis
My point is that readability should be first priority (until you find the code in question is the performance bottleneck, if performance becomes a problem). Modifying the list your are iterating over with aliasing may be a neat Perlish feature, but for me as a reader it seems a little magic.
asjo