in reply to have to Extract substring after '/' character

It's pretty easy to accomplish with Perl. The 'e' in Perl is rumored to stand for "extraction", after all. I think folks here have been hesitant to provide a cut-and-paste solution because the answer is so obvious to anyone who has spent more than a day or two learning Perl that it would probably only need to be asked by someone who is more interested in the answer than the learning. If we simply provide an answer without seeing any effort, you'll come back all too soon asking for another answer, and another, but never actually seeking wisdom. If we put more effort into providing answers than you put into learning to solve problems on your own in the future, we set ourselves up for frustration, and set you up for a lot of free solutions. We don't mind imparting knowledge, but we tire of doing people's work for free.

One of Perl's mantra's is "There is more than one way to do it." Just about any solution including the solution to your question falls into that category. However, the Perlish way to do it is probably to use a regular expression.

With regular expressions, you would want to match against your string $str, and capture into $1 the portion of the string you care about. You would want to test for the match, and possibly halt execution or spit out a warning if the match fails. If it succeeds, you would want to return the captured portion of the string.

So, the steps might look like this:

  1. Create a subroutine called get_path()
  2. Inside get_path(), put $_[0] into a variable $raw_string that is lexically scoped to the sub itself using my and =.
  3. Start an if(){} block. Inside the conditional you'll be testing $raw_string against a regular expression using the =~ operator followed by the m// operator. More on that later.
  4. In the success block, your sub will return the result contained in $1.
  5. In the failure block, your sub will die while spitting out a message such as "\$raw_string failed to match in get_path().\n$raw_string\n." You will probably want to allow the script's execution to terminate here since it's an indication that the train has gone off the rails.
  6. Your script itself will invoke the sub by passing it $str and assigning the outcome to $path.

That leaves the task of figuring out a regular expression to do the heavy lifting for you. Use capturing parenthesis. Within the capturing parens, anchor with '/', and follow that up with the token that can accept almost any input at all, in quantities of one character or more: '.+' Finally, anchor to the end of the line (or string) with a trailing '$' at the end of the pattern. Be sure to use alternate match delimiters, such as m{} because m// will run afoul of your specific first anchor (/).

Further reading: perlre, perlretut, die, perlsub, perlsyn, and of course perlintro.


Dave