Mac环境下Perl遍历文本文件行失败:while循环无法打印行内容
Hey there, let's figure out why your Perl scripts for processing file lines aren't working in TextWrangler on macOS Sierra 10.12.6. I've run into similar quirks before, so here are the most likely fixes and a solid example to get you going:
Common Issues & Fixes
Shebang Line Misconfiguration
macOS uses/usr/bin/perlas the default Perl path, so make sure your script starts with:#!/usr/bin/perlThis tells TextWrangler exactly which Perl interpreter to use—missing or incorrect paths can silently break execution.
File Path & Permission Problems
If your script can't find the file, double-check the path:- Use absolute paths (e.g.,
/Users/yourname/Documents/test.txt) instead of relative paths to avoid working directory confusion in TextWrangler. - Verify the file has read permissions: run
ls -l /path/to/your/file.txtin Terminal to check, and adjust withchmod +rif needed.
- Use absolute paths (e.g.,
TextWrangler Working Directory Mismatch
TextWrangler might run your script from a different directory than where your file lives. Add this line at the top of your script to confirm:print "Current working directory: ", `pwd`, "\n";If it's not the same as your file's folder, either use absolute paths or adjust TextWrangler's run settings (go to Run > Run Options to set the working directory).
Missing Strict/Warnings
Skippinguse strict;anduse warnings;hides critical syntax or variable errors. Always include these at the top of your script—they'll catch mistakes you might miss otherwise.
Working ProcessFile Subroutine Example
Here's a robust, tested script that should work in your setup:
#!/usr/bin/perl use strict; use warnings; sub ProcessFile { my ($filename) = @_; # Validate file exists and is readable unless (-e $filename && -r $filename) { warn "Error: Cannot access file '$filename' - $!\n"; return; } # Open file with a lexical filehandle (safer than global FH) open my $fh, '<', $filename or do { warn "Failed to open '$filename': $!\n"; return; }; # Traverse each line and process while (my $line = <$fh>) { chomp $line; # Remove newline characters # Add your string parsing logic here print "Processing line: '$line'\n"; # Example: Detect lines containing "example" (case-insensitive) if ($line =~ /example/i) { print "Found match: '$line'\n"; } } close $fh; } # Call the subroutine with your file path ProcessFile('/Users/yourname/Desktop/sample.txt');
How to Run in TextWrangler
- Save your script with a
.plextension (e.g.,file_processor.pl). - Use Run > Run Script (or press
Cmd + R). - Check the TextWrangler Console (Window > Show Console) for any error messages—this is where you'll see issues like "No such file or directory" or syntax errors.
If you still hit snags, share the error output from the console, and we can narrow it down further!
内容的提问来源于stack exchange,提问作者grumpy

