in reply to Re^2: Why do we need a \n with do FILENAME?
in thread Why do we need a \n with do FILENAME?

Since $! isn't set inside the file-to-be-evaluated, it must have been set by Perl while processing the file.

Yes, and completely irrelevant. $! cannot be used to determine if an error occurred.

Imagine that we are doing a file which (legally) returns undef, which might be reasonable if the code in the file is executed only for its side effects

No, it's not reasonable. The "do" module should return true on success just like "require" modules.

Replies are listed 'Best First'.
Re^4: Why do we need a \n with do FILENAME?
by rovf (Priest) on Jul 07, 2010 at 08:56 UTC
    The "do" module should return true on success
    May I ask how you could justify the should in your sentence? I read the perldoc again, but am unable to find any recommendation on the return value. In particular, it does not say that the user should signal an error by returning false. The only reference which I could found to require is, that do should not be used to load modules.

    IMHO, the best use for do is in those cases, where you want to evaluate at run-time Perl code which happens to be stored in a file. Without do, you would have to open the file, read it and eval the result. do is a shorthand way for doing this, but it means that a return value of undef (or other false value, such as 0 or '') should not be required to have a special meaning of 'failure'. The present implementation of do would nearly perfectly do this job, if it would not suffer from the single restriction that the caller can not distinugish between the case of the code in the filename returning undef, or Perl being unable to open the file. Moreover, this flaw in the implementation shows up only if the file does not end in a newline, and it would be easy to correct.

    So, technically speaking, you are right in that the documentation indeed allows for this behaviour. But isn't it a pity that we could make a function much more useful, by just a minor change in implementation? Anyway, the question which I used when starting this thread, is answered: It is not a bug, but undefined behaviour, and it means that I have to restrict what our users are permitted to place into the file which our application will do...
    -- 
    Ronald Fischer <ynnor@mm.st>

      May I ask how you could justify the should in your sentence?

      You've already explained why. If you return undef, you can't determine if an error occurred. As you put it, "the caller can not distinguish between the case of the code in the filename returning undef, or Perl being unable to open the file".

      It is not a bug, but undefined behaviour

      It's not undefined behaviour. The result of the function can be ambiguous, but the behaviour is defined.