行的末尾加上"->"吗
我在网上练习perl赋值,并在Sandbox中发现了这一点。
如何编写一个perl脚本,将->添加到前面并<-到每行的末尾。然后,它报告原始输入中的行数、最长行的长度和总字节数。例如,输入文件
//Input File
Hi there.
This is Fred.
Who are you?
应产生输出:
//Output File
->Hi there.<-
->This is Fred.<-
->Who are you?<-
3 lines, longest 13 characters, 37 bytes total.
我只能在代码为的行的开头添加->
#!/usr/bin/perl
use strict;
use warnings;
open(FH,"input.pl") or die "cannot open file: $!n"; #Input File
open(NEWFH,"> output.pl") or die "cannot writen"; #Output File
print "opened filen";
while(<FH>){
print NEWFH "-> $_ ";
}
close FH;
close NEWFH;
你能帮我在
作为一个练习,您可以使用以下一行代码并了解它们的工作原理:
perl -pe 's/^/->/; s/$/<-/;' input.txt
perl -ple '$_ = "->$_<-";' input.txt
对于更详细的版本,可以添加-MO=Deparse
开关。
推荐阅读:
- http://perldoc.perl.org/perlop.html#Quote-类似运算符
- http://perldoc.perl.org/perlre.html
- http://perldoc.perl.org/perlrun.html(或
perl -h
,用于命令行选项)
只需以相同的方式将其添加到行后,将其包含在打印字符串的末尾:
chomp; # Strip off newline character
print NEWFH "-> $_ <-n"; # Add newline ay the end
关于最长字符串和总数:您可以使用2个变量来存储当前的最大长度和当前总数,并在length
函数的帮助下计算它们。保留行计数的第三个变量。