ada has asked for the wisdom of the Perl Monks concerning the following question:

Hi perl peeps, I am trying to figure how this regex works:

/usr/bin/perl /usr/bin/ /perl / perl

if ($string =~ m#(\S*/)(\S*)#) { print "Path = $1, $Filename = $2\n"; } elsif ($string =~ /(\S+)/) { print "No path, Filename = $1\n"; }

Ok thanks everyone and for ur examples;

so in my example where the inbetween: (\S*)(\S*), does this cause the regex to jump down to the next line as there is just whitepace after the first capture/match?

x

Edit: g0n - code tags

Replies are listed 'Best First'.
Re: path extraction
by ikegami (Patriarch) on Dec 09, 2007 at 21:04 UTC
    Perl already comes with that functionality in the form of fileparse in File::Basename.
Re: path extraction
by GrandFather (Saint) on Dec 09, 2007 at 20:41 UTC

    Bottom line - it doesn't! \S matches non-whitespace characters and * means 'grab as many as you can', but if your path or filename contains whitespace characters then things turn a little pear shaped. Consider instead:

    use strict; use warnings; for my $string ( '/Unixish path/with/spaces in places/and a file name with spaces', 'file name only - with spaces', '/nice/no/spaces/path/and/filename' ) { if ($string =~ m!(.*/)?(.*)!) { print "Path = '$1', Filename = '$2'\n"; } elsif ($string =~ /(\S+)/) { print "No path, Filename = '$2'\n"; } }

    Prints:

    Path = '/Unixish path/with/spaces in places/', Filename = 'and a file +name with spaces' Path = '', Filename = 'file name only - with spaces' Path = '/nice/no/spaces/path/and/', Filename = 'filename'

    In any case you would generally be better to use File::Spec's splitpath.


    Perl is environmentally friendly - it saves trees
Re: path extraction
by mwah (Hermit) on Dec 09, 2007 at 20:31 UTC

    You need to modify the regex a little bit, like:

    ... my @strings = qw' /usr/bin/perl /usr/bin/ /perl / perl '; for my $string (@strings) { if( $string =~ m{^(.*/)(.*)$} ) { print "Path = $1, Filename = $2\n"; } elsif( $string =~ m{^([^/]+)$} ) { print "No path, Filename = $1\n"; } } ...

    (One variant of many, close to your original program.)

    Regards

    mwa