Special_K has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|