我对如何阅读文本文件的内容感到困惑。 我能够读取文件名但无法弄清楚如何获取内容。 顺便说一下,文件是加密的,这就是我试图解密的原因。
#!/Strawberry/perl/bin/perl use v5.14; sub encode_decode { shift =~ tr/A-Za-z/Z-ZA-Yz-za-y/r; } my ($file1) = @ARGV; open my $fh1, '<', $file1; while (<$fh1>) { my $enc = encode_decode($file1); print my $dec = encode_decode($enc); # ... do something with $_ from $file1 ... } close $fh1;I am confused on how to read the contents of a text file. I'm able to read the files name but can't figure out how to get the contents. By the way the file is encrypted that's why I'm trying to decrypt.
#!/Strawberry/perl/bin/perl use v5.14; sub encode_decode { shift =~ tr/A-Za-z/Z-ZA-Yz-za-y/r; } my ($file1) = @ARGV; open my $fh1, '<', $file1; while (<$fh1>) { my $enc = encode_decode($file1); print my $dec = encode_decode($enc); # ... do something with $_ from $file1 ... } close $fh1;最满意答案
这条线
my $enc = encode_decode($file1)将文件名传递给encode_decode
类似while ( <$fh1> ) { ... }的循环将文件中的每一行放入默认变量$_ 。 你自己写的评论“用$file1 from $file1做一些事情......” 。 你可能想要
my $enc = encode_decode($_)顺便说一下,您的encode_decode子例程不会反转自己的编码。 您已经编写了有效的ROT25编码,因此您必须应用encode_decode 26次才能返回到原始字符串
值得注意的是你的shebang线
#!/Strawberry/perl/bin/perl在Windows上没有意义,因为命令shell不处理shebang行。 Perl本身会检查行中是否有-w或-i等选项,但你不应该使用它们。 只需省略该行,或者如果您希望能够在Linux和Windows上运行您的程序,那么请使用
#!/bin/env perl这将导致Linux shell在PATH变量中搜索第一个perl可执行文件
This line
my $enc = encode_decode($file1)passes the name of the file to encode_decode
A loop like while ( <$fh1> ) { ... } puts each line from the file into the default variable $_. You've written so yourself in your comment “do something with $_ from $file1 ...”. You probably want
my $enc = encode_decode($_)And, by the way, your encode_decode subroutine won't reverse its own encoding. You've written what is effectively a ROT25 encoding, so you would have to apply encode_decode 26 times to get back to the original string
It's also worth noting that your shebang line
#!/Strawberry/perl/bin/perlis pointless on Windows because the command shell doesn't process shebang lines. Perl itself will check the line for options like -w or -i, but you shouldn't be using those anyway. Just omit the line, or if you want to be able to run your program on Linux as well as Windows then use
#!/bin/env perlwhich will cause a Linux shell to search the PATH variable for the first perl executable
更多推荐
发布评论