I am having difficulty creating a lazy match. Here is the code I have:


#!/tool/bin/perl -w use strict; my $test_filename = "/user1/lazy_match_test.txt"; my $match = ""; open(TEST_FILE, $test_filename) || die("ERROR: unable to open $test_fi +lename for read, exiting...\n"); while (<TEST_FILE>) { if ($_ =~ /\/(.+?)$/) { $match = $1; } } close(TEST_FILE); printf("matched $match\n");

Here are the contents of the test file:


/foo/bar/baz/bat

I am trying to write a pattern that captures what follows the last slash in the line.

My understanding is that the ? operator is used to tell perl that the previous pattern should be matched lazily, yet when I run the above code, $match is foo/bar/baz/bat, when I wanted bat.

How do I correctly implement the lazy operator? I know that in the above example there are other ways to capture bat without using a lazy operator, but for the sake of the discussion I would like to learn how the lazy operator works and why it isn't working in this case.

I also tried the following for my regex:

if ($_ =~ /\/(.+)?$/)

But it also matched foo/bar/baz/bat


In reply to help with lazy matching by Special_K

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.