programminglearner
programminglearner

Reputation: 542

Perl Join Array After Second Element

I want to get everything in a sentence after the second space. I am doing this by splitting and joining. I want to join everything after the second element but I'm not sure how to do this. The sentence can have several words so I don't want to hardcode the end range.

$sentence = "a b c and d";
@array = split(" ", $sentence);
$str = join(' ',$array[???]);

I want an output that looks like:

c and d 

Upvotes: 2

Views: 684

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185590

Using array slice :

use strict; use warnings;

my $sentence = "a b c and d";
my @array = split(" ", $sentence);
my $str = join(' ', @array[2 .. $#array]);
print "$str\n";

$#array is the number/key of the last element of the array.

Check https://perldoc.perl.org/perldata.html#Slices

Upvotes: 4

toolic
toolic

Reputation: 62227

If you don't need the array, you can split with a LIMIT, then just grab the last item (-1):

use warnings;
use strict;

my $sentence = "a b c and d";
my $str = (split /\s+/, $sentence, 3)[-1];
print "$str\n";

Upvotes: 5

Related Questions