EXtracting sub-string in Perl?

I have a string in a variable:

$mystr = "some text %PARTS/dir1/dir2/myfile.abc some more text";

Now %PARTS is literally present in the string, it is not a variable or hash. I want to extract the sub-string %PARTS/dir1/dir2/myfile.abc from it. I created the following reg expression. I am just a beginner in Perl. So please let me know if I have done anything wrong.

my $local_file = substr ($mystr, index($mystr, '%PARTS'), index($mystr, /.*%PARTS ?/));

I even tried this:

my $local_file = substr ($mystr, index($mystr, '%PARTS'), index($mystr, /.*%PARTS' '?/));

But both give nothing if I print $local_file. What might be wrong here? Thank You.

UPDATE: Referred the following sites for using this method:

  1. http://perlmeme.org/howtos/perlfunc/substr.html see example 1c
  2. How to take substring of a given string until the first appearance of specified character?

Answers


The index function returns the first index of the occurrence of a substring in a string, else -1. It has nothing to do with regular expressions.

Regular expressions are applied to a string with the bind operator =~.

To extract the matched area of a regular expression, enclose the pattern in parens (a capture group). The matched substring will then be available in $1:

my $str = "some text %PARTS/dir1/dir2/myfile.abc some more text";
if ($str =~ /(%PARTS\S+)/) {
  my $local_file = $1;
  ...; # do something
} else {
  die "the match failed"; # do something else
}

The \S character class will match every non-space character.

To learn about regular expressions, you can look at the perlretut.


The index function is not related to regexps. Its arguments are just strings, not regexps. So your usage is wrong.

Regexps are a powerful feature of Perl and the most appropriate tool for this task:

my ($local_file) = $mystr =~ /(%PARTS[^ ]+)/;

See perlop for more information on the =~ operator.


Need Your Help

Remove timezone format

java datetime calendar timezone jax-ws

I would like to know how could I remove the timezone automatically shown in my service output.

SSH: Don't prompt for password in shell script

linux bash ssh rsa-key-fingerprint

I'm using ssh and have a passwordless ssh setup for my system. Using ssh in a script works fine, but if the user specifies a host that don't has a passwordless ssh setup the script prompts for a pa...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.