sunil@perl has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I need to extract a part of a string. The strings are as below, /ba/mn/first one /ba/mn/second /ba/mn/third and so on. There are hundreds of such strings. I need to extract the below parts from the strings, first one second third and so on Can you monks please help me out in doing this as i am new to world of pattern matching and i am learning it. Thanks, Sunil.

Replies are listed 'Best First'.
Re: Pattern Matching
by Corion (Patriarch) on Apr 16, 2014 at 07:55 UTC

    The easiest way is File::Basename.

    But maybe you want to show us what code you already wrote and how it fails for you?

Re: Pattern Matching
by kcott (Archbishop) on Apr 16, 2014 at 09:49 UTC

    G'day Sunil,

    As already pointed out, your unformatted data is problematic; however, you may find that split is sufficient for your needs.

    $ perl -le 'print +(split /\//)[-1] for ("/ba/mn/first one", "/ba/mn/s +econd")' first one second

    -- Ken

Re: Pattern Matching
by Anonymous Monk on Apr 16, 2014 at 07:57 UTC
    Path::Tiny for all your needs
    $ perl -l - use Path::Tiny qw/ path /; print path( '/anything/you/want' )->basename; __END__ want
Re: Pattern Matching
by AnomalousMonk (Archbishop) on Apr 16, 2014 at 13:56 UTC

    Given a constant prefix and no terminating suffix (i.e., terminates at end of string) (5.10+ needed for \K):

    c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; my @strings = ('/ba/mn/first one', '/ba/mn/second', '/ba/mn/third'); ;; my $prefix = qr{ /ba/mn/ }xms; ;; for my $s (@strings) { printf qq{string '$s' -> parts }; my @parts = $s =~ m{ $prefix \K .* }xmsg; printf qq{'$_' } for @parts; print ''; } " string '/ba/mn/first one' -> parts 'first one' string '/ba/mn/second' -> parts 'second' string '/ba/mn/third' -> parts 'third'
Re: Pattern Matching
by Laurent_R (Canon) on Apr 16, 2014 at 09:37 UTC
    Please use code tags <c> and </c> for your example data, this will make it easier to understand it.
Re: Pattern Matching
by Anonymous Monk on Apr 16, 2014 at 13:49 UTC
    split() will probably do the job nicely. Remember that Perl array indexes start with zero. While writing a program that will deal with "hundreds of" such strings, be sure also to write your program in such a way that it aggressively looks for situations that it does not expect to see, and die()s whenever appropriate. When inputs are complex and come in many different flavors, it is very, very easy to write code that "seems to" work.