Cool_Coder
Cool_Coder

Reputation: 5073

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?

Upvotes: 2

Views: 5242

Answers (2)

amon
amon

Reputation: 57590

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.

Upvotes: 4

dolmen
dolmen

Reputation: 8696

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.

Upvotes: 3

Related Questions