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

I'm trying to open a file and print to it. I put a die command if the file couldn't be appended. Below is my code and the error that I received.

select BEDROCK if (! open BEDROCK, ">>/home/barney/.error_log") { die "Cant open file: $!"; } print "I hope MR. Slate doesnt find out about this \n"; print "Wilma! \n"; syntax error at ./Page_100 line 10, near ") {" Execution of ./Page_100 aborted due to compilation errors.

Thanks in advance Catfish

Replies are listed 'Best First'.
Re: Open Error
by LanX (Saint) on Nov 26, 2018 at 16:26 UTC
    The semicolon after select statement is missing.

    Perl reads

    select BEDROCK if (! open BEDROCK, ">>/home/barney/.error_log") ... Oops.

    update

    HINT: using an editor doing auto-indentation would have shown it.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: Open Error
by Eily (Monsignor) on Nov 26, 2018 at 16:58 UTC

    While your code works (edit: well, when you add the missing ';' at least) there are some things you can do to make your life easier. The first one is to use a scalar instead of a bareword for the file handle (use a variable starting with a $ rather than the word BEDROCK). Second, you can have the open mode in a separate argument rather than with the file path. Third, while selecting the handle before opening it works, it's clearer if you do it after. So:

    select BEDROCK; # BEDROCK doesn't exist yet open BEDROCK, ">>/home/barney/.error_log";
    Becomes:
    open my $bedrock, ">>", "/home/barney/.error_log"; select $bedrock;
    It will make it much easier for perl to tell you when you have made a typo (if you use strict). Otherwise, typing BEDROCK once and BERDOCK the second time will compile but fail to work.

    Also, it's considered good practice to avoid having things happen inside the condition of an if statement (it's ok to check things, but not to change them). The open line could be rewritten like this:

    open my $bedrock, ">>", "/home/barney/.error_log" or die "Can't open f +ile: $!";
    (as a matter of fact, that's how I do it most of the time). But you could also add use autodie; at the top of your program, and it will make report errors automatically, without you having to write the die part by hand.