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


Hi Monks,

I want to match the first occurance of a pattern in a string.

For example:

my $string="/ae/gowtham_langTests/hpgl2/hpgl2/linepath/masters/top2bottom/top2bottom9/top2bott om9.plt1.tiff ";

my $pattern = "/hpgl2/";

I want to match the first occurance of "$pattern" in the string "$string".

Can any one help me on this?

Thanks in advance....

Regards,

Anand.

Replies are listed 'Best First'.
Re: First occurance in a string
by parv (Parson) on Aug 29, 2008 at 06:11 UTC
    See index function: index 'p q' , 'q' will return 2 (success), while index 'p q' , 'r' will return -1 (failure).
Re: First occurance in a string
by kyle (Abbot) on Aug 29, 2008 at 14:49 UTC

    If $pattern is a literal string to find in $string, then parv is correct. Use index.

    If $pattern is really a pattern and not a literal string to find in $string, you can do something like this:

    my $string="/ae/gowtham_langTests/hpgl2/hpgl2/linepath/masters/top2bot +tom/top2bottom9/top2bott om9.plt1.tiff "; my $pattern = "/hpgl2/"; if ( $string =~ /\A(.*?)$pattern/ ) { print "place: ", length $1, "\n"; } print "index: ", index( $string, $pattern ), "\n"; __END__ place: 21 index: 21
      As a variation, the @- 'match start' variable can be used (see perlvar):

      perl -wMstrict -le "my $string = 'foo/bar/pattern/baz/pattern/quux'; my $pattern = qr{ pat{2}ern }xms; if ($string =~ m{ ($pattern) }xms) { print qq(start: $-[1]); } else { print 'pattern not found'; } my $idx = index $string , 'pattern'; print qq(index: $idx); " start: 8 index: 8

      Update:

      As per the documentation, a hyphen renders as a space in [doc://name#anchor] links. How can I get a hyphen to render as a hyphen? (Thanks toolic — @- looks like @- now.)

        How can I get a hyphen to render as a hyphen?
        Here is one way: [doc://perlvar#@-|@-]

        @-