在 Perl 中使用 -s 获取文件大小

发布于 2024-09-16 04:14:37 字数 352 浏览 7 评论 0原文

我正在尝试使用 -s 运算符查找文件的大小。它看起来像这样:

my $filesz = -s $filename

我尝试了很多不同的方法,但它无法得到这个大小。
但是,如果我提供静态内容而不是文件名,它就可以正常工作

例如:

$filesz = -s "/tmp/abc.txt"

这可以正常工作。

我尝试在文件名中添加 ",但没有成功。我使用 chomp 从文件名中删除了 \n,但问题仍然存在这是怎么回事?

I am trying to find the size of a file using the -s operator. It looks like this:

my $filesz = -s $filename

I tried lots of various way, but it can not get this size.
However, if I give static content instead of filename, it works fine

For example:

$filesz = -s "/tmp/abc.txt"

This works fine.

I tried adding " in the filename, it didn't work. I removed \n from filename using chomp, but the problem remains the same. What's wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

贵在坚持 2024-09-23 04:14:37

-s $filename 工作得很好;唯一的结论是 $filename 中不存在其名称的文件。仔细查看 $filename 的内容,并确保您的工作目录是您认为的目录。

-s $filename works just fine; the only conclusion is that there's no file with the name contained in $filename. Take a very close look at the contents of $filename, and make sure that your working directory is what you think it is.

ら栖息 2024-09-23 04:14:37

正如霍布斯所说,最可能的解释是 $ filename 不包含您认为的内容。

根据以前的经验,我会更进一步,并犹豫是否猜测 $filename 末尾有一个换行符。您是从文件还是用户输入中读取 $filename 中的值?

As hobbs says, the most likely explanation is that $filename doesn't contain what you think it does.

Based on previous experience, I'd go further than that and hesitate a guess that $filename has a newline character at the end of it. Are you reading the value in $filename from a file or from user input?

香草可樂 2024-09-23 04:14:37

我认为你应该尝试从 readdir 中获取:

#!/usr/bin/perl -w

use strict;
use warnings;

my $filedir = "/documents/sample/file.txt";


opendir(my $dir, $filedir) or die "Could not load directory";
my @read_dir = sort grep {!-d}readdir($dir);
foreach my $fileInDir(@read_dir)
{

    my $currentDestination = "$filedir/$fileInDir";
    my $filesize = -s $currentDestination;

    if(-z $currentDestination)
    {
       print "Zero -  Filename: $fileInDir Size: $filesize\n";
    }
    else
    {
        print "Non - Zero Filename: $fileInDir Size: $filesize\n";
    }

}

i think you should try this your getting from a readdir:

#!/usr/bin/perl -w

use strict;
use warnings;

my $filedir = "/documents/sample/file.txt";


opendir(my $dir, $filedir) or die "Could not load directory";
my @read_dir = sort grep {!-d}readdir($dir);
foreach my $fileInDir(@read_dir)
{

    my $currentDestination = "$filedir/$fileInDir";
    my $filesize = -s $currentDestination;

    if(-z $currentDestination)
    {
       print "Zero -  Filename: $fileInDir Size: $filesize\n";
    }
    else
    {
        print "Non - Zero Filename: $fileInDir Size: $filesize\n";
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文