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

时间:2011-06-23 19:36:19

标签: 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

有人可以帮我完成这项非常简单的任务吗?另外,当它提到$“变量时它意味着什么?提前谢谢。

2 个答案:

答案 0 :(得分:3)

也许您应该查看$" variable in perldoc perlvar并查看其功能。如果你这样做,其余的很容易。

答案 1 :(得分:3)

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

  

这是数组变量时列表元素之间使用的分隔符   被插入到双引号字符串中。通常,它的值是一个空格   字符。

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

SPOILER ALERT

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

SPOILER ALERT

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

[/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

请注意,元素之间添加了空格?这是因为当我们将数组插入到字符串上下文中时,$"变量起作用,并在连接时在每个元素之间添加一个空格。我们需要做什么 next 将该空间改为“#”。我们可以在打印前更改$"变量来执行此操作:

[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