2

Why is this example not working?

#!/usr/bin/perl
use POSIX qw(strftime);
use Time::Local;

my $date = strftime "%Y-%m-%d", localtime;
my $command = "ls clients/*/ERRORi/" . $date . "/*s";

@result = `$command`;

foreach $group (@result) {
  my $file = '/opt/' . $group;
  open( my $input_fh, '<', $file) || die "Can't open $file: $!";
  print $input_fh;
}

it will return:

Can't open /opt/clients/cli8832/ERRORi/2014-06-25/file.564159972s
: No such file or directory at ./my.pl line 12.

but if I do ls /opt/clients/cli8832/ERRORi/2014-06-25/file.564159972s it works

1
  • 2
    The formatting of the error message is a good clue here. Your $file has a newline in it. Commented Jun 26, 2014 at 12:46

2 Answers 2

8

Your $file variable contains a trailing linefeed character, whereas your actual file name doesn't.

Your ought to chomp it out.

Sign up to request clarification or add additional context in comments.

Comments

2

That's a poor example to be learning from.

  • Include use strict; and use warnings in EVERY perl script.
  • Include use autodie; anytime you're doing file processing
  • And finally, instead of shelling out to ls, just use a file glob. This will remove the need to chomp.

Then following is a cleaned up version of that example, although the last line is probably also a bug.

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

use POSIX qw(strftime);
use Time::Local;

my $date = strftime "%Y-%m-%d", localtime;

for my $group (glob "clients/*/ERRORi/$date/*s") {
    my $file = '/opt/' . $group;
    open my $input_fh, '<', $file;
    print $input_fh;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.