Perl 循环设施与控制指令详解
1. 循环基础
在处理文件内容时,Shell 和 Perl 有不同的循环处理方式。在 Shell 中,若要逐行处理文件内容,可使用如下代码:
OIFS="$IFS" # save for restoration
IFS='
' # Internal Field Separator is now "carriage return"
for line in `cat somefile` # or: `cmd1 | cmd2`, etc.
do
IFS="$OIFS" # reinstate original setting ASAP
echo "Processing $line"
# Processing code goes here
done
此代码先保存原有的内部字段分隔符(IFS),将其设置为换行符,以便逐行读取文件内容。处理每行内容后,恢复原有的 IFS 设置。
而在 Perl 中,若文件名需在脚本运行时由用户输入,可使用以下代码:
printf 'Enter filename: '; # prompt for input
$filename=<STDIN>; # store the filename
defined $filename or exit; # exit on <^D>
chomp $f
超级会员免费看
订阅专栏 解锁全文
34

被折叠的 条评论
为什么被折叠?



