Does the last keyword only care about braces when determining what constitutes a loop? I have the following code:
#!/usr/bin/perl -w use strict; my $last_test_file = "./last_test_file"; printf("before loop\n"); while (1) { if (open TEST_FILE, $last_test_file) { printf("after open\n"); /^\s*TEST_PATTERN\s+/ and last while <TEST_FILE>; printf("after match\n"); close(TEST_FILE); } else { die("ERROR: Unable to open $last_test_file for read, exiting.. +.\n"); } } printf("after loop\n");
Assume last_test_file contains the text TEST_PATTERN on line 6, and non-matching text on all other lines. My expectation is that the above script will open last_test_file, read the first 5 lines without matching, then read line 6, match, exit the inner while loop due to the 'last' statement, print "after match", close the file handle, and repeat this process indefinitely due to being stuck in the while(1) loop. What happens in actuality is the script never makes it to the "after match" text; the 'last' statement appears to be breaking out of the outer while (1) loop rather than the inner while <TEST_FILE> loop. If I replace the single-line while loop above with the following:
while (<TEST_FILE>) { /^\s*TEST_PATTERN\s+/ and last; }
The script behaves as I described above, i.e. it remains stuck inside the while (1) loop and the 'last' statement only breaks out of the while (<TEST_FILE>) loop. This occurs with perl 5.26.1.
Here are my questions:
1. Does 'last' use the presence of braces to determine what constitutes a loop? Does 'last' officially not work with single-line while loops like the above? I was not able to determine this from the perldoc page for 'last' (http://perldoc.perl.org/functions/last.html).
2. Are single-line while loops like the one above considered bad programming practice in general?
3. I am running with "use strict" and warnings enabled. Shouldn't my single-line while loop with 'last' be flagged at least as a warning, given that the last statement doesn't apply to the loop it is used within? Is there any higher level of warning that can be enabled to catch things like this?
In reply to Use of 'last' within single-line while loops by Special_K
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |