in reply to First occurance in a string

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

Replies are listed 'Best First'.
Re^2: First occurance in a string
by AnomalousMonk (Archbishop) on Aug 29, 2008 at 15:51 UTC
    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#@-|@-]

      @-