I have an array of strings: @array
I want to concatenate all strings beginning with array index $i to $j.
How can I do this?
$newstring = join('', @array[$i..$j])
$#array is a shorter way of saying scalar@array - 1@array-1 == $#array, somebody pointed out that "not if $[ has been changed". Admittedly, an odd scenario that we usually don't even care to think about, most of the time...@array, you write $#array because it means the last index in @array. You don't write @array - 1 because that means "one less than the number of things in @array".Just enclosing a perl array in quotes is enough to concatenate it, if you're happy with spaces as the concatenation character:
@array = qw(a b c d e f g);
$concatenated = "@array[2 .. 5]";
print $concatenated;
## prints "c d e f"
or of course
$" = '-';
@array = qw(a b c d e f g);
$concatenated = "@array[2 .. 5]";
print $concatenated;
if you'd prefer "c-d-e-f".
Try this ....
use warnings ;
use strict ;
use Data::Dumper ;
my $string ;
map { $string .= $_; } @arr[$i..$j] ;
print $string ;
map in void context; a for loop would work just as well. But loops of any sort are unnecessary when you can just use join.map evil? I'd use a postfix for most places a void map can be used. Here I'd use a join. But Perl 5.8.1 and up optimize away map's return values when called it is called in void context. For more discussion of map in void context see: perlmonks.org/index.pl?node_id=296742