如何读取文件的内容(How to read the contents of a file)

编程入门 行业动态 更新时间:2024-10-09 23:13:42
如何读取文件的内容(How to read the contents of a file)

我对如何阅读文本文件的内容感到困惑。 我能够读取文件名但无法弄清楚如何获取内容。 顺便说一下,文件是加密的,这就是我试图解密的原因。

#!/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/perl
 

is 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 perl
 

which will cause a Linux shell to search the PATH variable for the first perl executable

更多推荐

本文发布于:2023-08-07 16:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   内容   read   contents   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!