15

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?

4 Answers 4

23
$newstring = join('', @array[$i..$j])
Sign up to request clarification or add additional context in comments.

5 Comments

thanks. if $j is end of string, i am using scalar(@array)-1 for $j. is there any other way of doing that.
@iamrohitbanga Yes: $#array is a shorter way of saying scalar@array - 1
Sorry I don't follow the "$j is end of string" part. But scalar(@array)-1 is $#array.
The last time I said that @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...
The point is to use the one that means what you want. Since in this case you want the last thing in @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".
10
my $foo = join '', @array[$i..$j];

First we generate an array slice with the values that we want, then we join them on the empty character ''.

Comments

2

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".

Comments

-1

Try this ....

use warnings ;
use strict ;
use Data::Dumper ;
my $string ;
map { $string .=  $_; } @arr[$i..$j] ;
print $string ;

2 Comments

You shouldn't use 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.
Is void 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

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.