Rohit Banga
Rohit Banga

Reputation: 18918

How can I use Perl to concatenate array elements between two indexes?

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?

Upvotes: 15

Views: 30155

Answers (4)

dsolimano
dsolimano

Reputation: 8986

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

Upvotes: 9

AmbroseChapel
AmbroseChapel

Reputation: 12087

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

Upvotes: 2

Pavunkumar
Pavunkumar

Reputation: 5335

Try this ....

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

Upvotes: -1

xiechao
xiechao

Reputation: 2361

$newstring = join('', @array[$i..$j])

Upvotes: 22

Related Questions