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

Hi monks. I know a little English :( Below is my code. I want to get $path from $target. How I do it in one regexp? Thanks :)
#!/bin/env perl use strict; use warnings; my $target = "/index.php?prefix=/user/"; my $path = $target; # How to optimize? $path =~ s{\?.*$}{}; $path =~ s{[^/]+$}{}; print "$path\n";

Replies are listed 'Best First'.
Re: How to replace in one regexp
by Sue D. Nymme (Monk) on Sep 30, 2009 at 17:37 UTC

    Written as two statements, your expressions are clear. Why confuse the issue by writing them as one?

    "Optimize" does not mean "use as few statements as possible."

Re: How to replace in one regexp
by Anonymous Monk on Sep 30, 2009 at 15:27 UTC
    CGI, URI
    #!/usr/bin/perl -- use strict; use warnings; use URI; my $path = { URI->new( "/index.php?prefix=/user/" )->query_form }->{pr +efix}; print "$path\n"; use CGI; $path = CGI->new( "prefix=/user/")->param("prefix"); print "$path\n"; __END__ /user/ /user/
      Good call to use URI, but your code does something different than the OP's. The following would be equivalent:
      #!/bin/env perl use strict; use warnings; use URI qw( ); my $target = "/index.php?prefix=/user/"; my $path = URI->new_abs( '.', $target )->path(); print "$path\n";
Re: How to replace in one regexp
by appleii (Novice) on Sep 30, 2009 at 16:51 UTC
    $path = substr($path, 0, rindex($path, "/", ($_ = rindex($path, "?")) +!= -1 ? $_ : length($path)) + 1);
Re: How to replace in one regexp
by JavaFan (Canon) on Sep 30, 2009 at 16:18 UTC
    I want to get $path from $target. How I do it in one regexp?

    # How to optimize?

    Those are two different questions, and are likely to have different answers. I would leave it as is, but if you insist on using one regexp, I guess (haven't tried it), something like:
    $path =~ s/(?:[^/]*\?.*$)|(?:[^/]+$)/;
Re: How to replace in one regexp
by vitoco (Hermit) on Sep 30, 2009 at 16:27 UTC
    my $path = $1 if $target =~ m!^([^?]*?/)?([^/\?]*)(\?(.*))?$!;
    • $1 : path
    • $2 : file or script name
    • $3 : query string
    • $4 : query string without leading "?"
Re: How to replace in one regexp
by vitoco (Hermit) on Oct 01, 2009 at 21:46 UTC
    #$path =~ s{\?.*$}{}; #$path =~ s{[^/]+$}{}; $path =~ s{[^/\?]*(\?.*)?$}{};