繁体   English   中英

如何使用Perl从带有前导字符串的文件中打印行?

[英]How to print lines from a file with a leading string using Perl?

我是Perl的新手。 我已经开始本教程http://www.comp.leeds.ac.uk/Perl/ 文件处理部分有一个练习,内容为:

修改上面的程序,以便在每行的开头打印一个带有#符号的整个文件。 您只需要添加一行并修改另一行即可。 使用$“变量。

这是程序:

#!/usr/local/bin/perl
#
# Program to open the password file, read it in,
# print it, and close it again.

$file = '/etc/passwd';      # Name the file
open(INFO, $file);      # Open the file
@lines = <INFO>;        # Read it into an array
close(INFO);            # Close the file
print @lines;           # Print the array

有人可以帮我完成这个非常简单的任务吗? 另外,提到$“变量是什么意思?

也许您应该在perldoc perlvar中查找$"变量并查看其作用。如果这样做,其余的工作就很简单。

这样做的关键是理解$"变量的用法(注意:这与$_变量不同。) $"变量:

这是在将数组变量内插到双引号字符串中时在列表元素之间使用的分隔符。 通常,其值为空格字符。

这是什么意思? 这意味着存在一种将项目数组转换为字符串上下文的方法,其中每个项目都由一个特殊字符分隔。 默认情况下,特殊字符是空格...但是我们可以通过更改$"变量来更改特殊字符。

踏板警报

以下文本包含该练习的解决方案!

踏板警报

因此,本练习的第一部分是在字符串上下文而不是数组中打印文件。 假设我们有一个伪文件,其内容为:

[/etc/passwd]
User1
User2
User3

[exercise.pl]
#!/usr/local/bin/perl   
#   
# Program to open the password file, read it in,   
# print it, and close it again.      
$file = '/etc/passwd';      # Name the file   
open(INFO, $file);          # Open the file   
@lines = <INFO>;            # Read it into an array   
close(INFO);                # Close the file   
print "@lines";             # Print the array   <---- Notice the double quotes

[RESULT]
User1
 User2
 User3

注意元素之间是否添加了空格? 这是因为当我们在阵列内插成一个字符串背景下, $"变量进场,并在它被串接各元素之间添加一个空格。我们下一步需要做的是改变空间变成一个‘#’。我们可以在打印之前更改$"变量以执行以下操作:

[exercise.pl]
#!/usr/local/bin/perl   
#   
# Program to open the password file, read it in,   
# print it, and close it again.      
$file = '/etc/passwd';      # Name the file   
open(INFO, $file);          # Open the file   
@lines = <INFO>;            # Read it into an array   
close(INFO);                # Close the file
$" = "#";                   # Change $"         <---- This line has been added!
print "@lines";             # Print the array   <---- Notice the double quotes

[RESULT]
User1
#User2
#User3

好吧! 我们快到了。 最后一点是在第一行的前面加上一个“#”。 因为$"更改了元素之间的分隔符 ,所以它不会影响第一行!我们可以通过更改print语句以先打印”#“,然后再打印文件内容来完成此操作:

[exercise.pl]
#!/usr/local/bin/perl   
#   
# Program to open the password file, read it in,   
# print it, and close it again.      
$file = '/etc/passwd';      # Name the file   
open(INFO, $file);          # Open the file   
@lines = <INFO>;            # Read it into an array   
close(INFO);                # Close the file
$" = "#";                   # Change $"         <---- This line has been added!
print "#" . "@lines";       # Print the array   <---- Notice the double quotes

[RESULT]
#User1
#User2
#User3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM