Reputation: 21666
Say I have an array which has the below data
@array = ('/root/level1','/root/level2',
'/root/level1/level2','/root/level1/level2/level3')
I want to loop over this array and replace each element with its last word as
@array = ('level1','level2','level2','level3')
I am not good with regex, can anyone help?
Upvotes: 0
Views: 167
Reputation: 67900
Why use regex when you have the File::Basename
module to do the work for you. It is a core module in Perl 5.
use strict;
use warnings;
use Data::Dumper;
use File::Basename;
my @array = ('/root/level1',
'/root/level2',
'/root/level1/level2',
'/root/level1/level2/level3');
@array = map basename($_), @array;
print Dumper \@array;
Output:
$VAR1 = [
'level1',
'level2',
'level2',
'level3'
];
Upvotes: 3
Reputation: 16984
Using split and map:
@array=map{(split(/\//,$_))[-1]}@array;
Using regex:
@array=map{m|.*/(.*)|}@array;
Upvotes: 5