in reply to Extract portion of string based on string separator

The following two also works:

my ($y) = '/a/b/c/d/e/f' =~ m{^(/[^/]+/[^/]+/[^/]+)};
my $y = join('', (split(qr{(?=/)}, '/a/b/c/d/e/f'))[0..2]);

By the way, using $a is a bad habit. Declaring it as a lexical, doubly so.

Replies are listed 'Best First'.
Re^2: Extract portion of string based on string separator
by Krambambuli (Curate) on Apr 26, 2007 at 08:07 UTC
    Depending a bit on whom eyes for your code goes, you might want to restyle ikegami's first suggestion above to something like
    use strict; use warnings; my $path_head = _get_first_3( '/a/b/c/d/e/f' ); sub _get_first_3 { my ($path) = @_; my $path_part = qr{ [^/]+ }x; # whatever char except slash my $path_head_regex = qr{ ( \A # beginning of string ( / $path_part) {3} ) # /three/part/parts here }x; my ($head) = ($path =~ m{ $path_head_regex }x); return $head; }
      ikegami,GrandFather and Krambambuli,

      Thank you very much for the insightful solutions. I particularly liked Krambambuli's method of writing a subroutine for extracting the first n members. I have yet to understand how it works though.

      Best Regards,