-5

What am I doing wrong? I've tried many things but can't seem to read from this file. Thanks!

my $d = 'URLs.txt';
open(my $fh, '<:encoding(UTF-8)', $d)
#opendir(D, "$d") || die "Can't open directory $d: $!\n";
  or die "Can't open directory $d: $!\n";

my @list = readdir($fh);
closedir($fh);

foreach my $f (@list) {


my $json_data = get "$f";
my $json_obj = new JSON;
my $URLdata = $json_obj->decode($json_data);

  return $URLdata->{'status'} eq 'UP';
}
PerlDuck
  • 5,610
  • 3
  • 20
  • 39
Kevin
  • 1
  • 1

2 Answers2

5

URLs.txt appears to be a file, not a directory

To open a file, write

open my $fh, '<', $filename or die $!;

and read from it with

while ( my $line = <$fh> ) { ... }

To open a directory, write

opendir my $dh, $dirname or die $!;

and read its contents with

while ( my $item = readdir $dh ) { ... }

If you had use strict and use warnings 'all' in place as you should in every Perl program you write you would have seen

readdir() attempted on invalid dirhandle $fh
closedir() attempted on invalid dirhandle $fh

which would have guided you towards the problem

You may be better of with other functions, depending on what it is you want to do

Borodin
  • 126,100
  • 9
  • 70
  • 144
0

Your variable names are not great, to put it mildly. Let's fix that!

use strict;
use warnings;

use JSON;
use LWP::Simple;

my $file = 'URLs.txt';

open(my $fh, '<:encoding(UTF-8)', $file) or die "Can't open file $file: $!\n";
chomp(my @lines = <$fh>);
close($fh);

foreach my $url (@lines) {
    my $json_text = get($url);

    if (defined($json_text)) {
        my $perl_ref = decode_json($json_text);

        if ($perl_ref->{status} eq 'UP') {
            print "foo\n";
        }
    } else {
        # handle the error!
    }
}

You'll notice I also:

  • Added use strict and use warnings, which should be in every Perl file you write
  • Added error-checking to the LWP get() result
  • Removed indirect object notation (new JSON) in favor of the decode_json() convenience function. It's the same as JSON->new->utf8->decode(), only shorter.
  • Removed the return statement, because it doesn't make any sense outside of a subroutine. If this code has actually been yanked from a subroutine, then you should show that as part of your MCVE.
Matt Jacob
  • 6,503
  • 2
  • 24
  • 27
  • Thank you for your response! What I am trying to do is call this perl script from another javascript and return the boolean. Do you know if this is possible? – Kevin Jun 23 '17 at 14:01