tuvalb has asked for the wisdom of the Perl Monks concerning the following question:

Hi, very new to Perl... trying to run:
#!/usr/bin/perl open (FILE, 'data.txt'); while (<FILE>) { chomp; ($name, $email, $phone) = split("\t"); print "Name: $name\n"; print "Email: $email\n"; print "Phone: $phone\n"; print "---------\n"; } close (FILE); exit;
but then I get: readline() on closed filehandle FILE at Readfile1.pl line 4 why is that? what's wrong? 10x, Tuval

Replies are listed 'Best First'.
Re: can't open a file?
by Bloodnok (Vicar) on Oct 01, 2009 at 22:40 UTC
    It's not unlike the call to open failed, but your script failed to notice and act accordingly e.g. by dieing.

    Try, at line 2, inserting

    use warnings; use strict; use autodie;
    . These 3 lines will have the effect of
    • giving you a heads-up on any potential problems,
    • telling you of any scripting errors and finally,
    • causing the script to die with an explanation if a system call e.g. the aforementioned open(), fails for any reason.

    A user level that continues to overstate my experience :-))
Re: can't open a file?
by Anonymous Monk on Oct 01, 2009 at 22:35 UTC
    You're not doing any error checking. perldoc -f open
    open(my $fh, '<', "input.txt") or die $!; and for writing: open(my $fh, '>', "output.txt") or die $!;
    Or
    use autodie;
Re: can't open a file?
by ikegami (Patriarch) on Oct 02, 2009 at 04:33 UTC

    Quick tip: split's first arg is a regex pattern. It doesn't match the string literally. Use a match operator instead of a string, and you'll avoid future confusion.

    my ($name, $email, $phone) = split(/\t/);

    I also noticed your script lacks use strict; use wanrings;. Please use them. Not using them hides errors. This one's important.

Re: can't open a file?
by leocharre (Priest) on Oct 02, 2009 at 15:57 UTC
    This note is to echo what ikegami said- This is one of the most important things you have to do as you learn perl.. 'use strict;' - use that. Just believe..

    Here's your script rewritten with strict.. (untested)

    #!/usr/bin/perl use strict; open (FILE, 'data.txt'); while (<FILE>) { chomp; my ($name, $email, $phone) = split(/\s/); # split on whitespace print "Name: $name\n"; print "Email: $email\n"; print "Phone: $phone\n"; print "---------\n"; } close (FILE); exit;