http://qs321.pair.com?node_id=11108517


in reply to matching substring in url

ciaoperl:

Yet another way you could do it:

echo "$XXX" | perl -pe '$_=(split "/", (split ";")[0])[-1]'

It might look a little magical at first, but it's actually pretty simple. Instead of using a regular expression, I first split the string on ";" and kept only the first bit ((split ";")[0]) to chop off the optional bits. Then I split that first bit on "/" and kept the last part ((split "/", ...)[-1]) to get the value you wanted. Finally, I assigned the result to $_ and used the -p option to print the value.

I got there essentially by starting with something like this:

my $url = "/bla/bla/123;yarg"; my @tmp = split ";", $url; # break string at semicolons @tmp = split "/", $tmp[0]; # break first chunk apart at "/" print $tmp[-1]; # Print the value we want

Since you can extract a chunk of a list by subscripting it, I first contracted the above to:

my $url = "/bla/bla/123;yarg"; # Split on ";", keep only the first chunk, then split on "/" my @tmp = split "/", (split ";", $url)[0]; # The last item holds the value we want print $tmp[-1];

Then I wanted to get rid of the temporary array by keeping *only* the final result by again subscripting the resulting list:

my $url = "/bla/bla/123;yarg"; $url = (split "/", (split ";", $url)[0])[-1]; print $url;

Then to turn it into a one liner, I changed it to this:

perl -e '$a="/bla/bla/123;yarg"; print (split "/", (split ";", $a)[0]) +[-1]' print (...)_ interpreted as function at -e line 1. syntax error at -e line 1, near ")[" execution of -e aborted due to compilation errors.

Oops! The parser sees "print (" and thinks we're wrapping the print arguments in parenthesis, leading to a syntax error later. I could've fixed the problem by putting a unary "+" on the thing to print, as that tells perl that the parenthesis isn't part of print:

perl -e '$a="/bla/bla/123;yarg"; print +(split "/", (split ";", $a)[0] +)[-1]' 123

But I went a different route: since you're using echo to inject the value into perl as the value $_, I instead elected to use the -p option which tells perl to print the value in $_ after the code executes, giving me the bit of code I suggested.

...roboticus

When your only tool is a hammer, all problems look like your thumb.