Chankey Pathak
Chankey Pathak

Reputation: 21666

Search and replace in an array

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

Answers (2)

TLP
TLP

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

Guru
Guru

Reputation: 16984

Using split and map:

@array=map{(split(/\//,$_))[-1]}@array;

Using regex:

@array=map{m|.*/(.*)|}@array;

Upvotes: 5

Related Questions