in reply to Re: readdir return nul string
in thread readdir return nul string

Erm, that chomp in there is rather spurious. 99.99% of the time you're not going to have newlines on the end of filenames so it's useless overhead. And the remaining .01% of the time when you actually did have a newline on the end of the filename post-chomp you now no longer have the actual file name in your list.</nit>

(And you really want or not || in your opendir line.)

Replies are listed 'Best First'.
Re^3: readdir return nul string
by Aim9b (Monk) on Sep 26, 2007 at 18:50 UTC
    Fletch, thanks for the tips. Can you explain a little further, the whys & wherefores? The examples I used for the open were files, not dirs. Is that the difference. Files use || & dirs use 'or', or is it something else?
    If I'm building a list of files to open, I wouldn't think I would EVER want the newline there. I used the chomp over the chop for just that reason, so I wouldn't lose a significant character of the name.

    Thanks.

      It's a matter of precedence: || binds "tighter" than or so you've in effect written opendir( FOO, ( "." || die "..." ) ). The die is silently optimized away since it can never be reached (since the constant "." will never be false). See perlsyn for more details.

      As for newlines, while it's not common there's nothing (at least on POSIX systems; I'm sure someone will chime in about Wintendo land . . .) that prevents you from having a newline character in a filename. You can make one yourself with perl -e 'open( my $f, ">", "foo\n" )' (and then when you do an ls you'll see something like foo?, or foo\n if your ls supports the -b flag).

      At any rate, my point was that in the majority of cases you're not going to have a newline on the end of a filename so calling chomp is wasted effort. In the rare case where some joker did go and put a newline (or some other wonky character) into a filename if you muck with it to remove newlines or what not you no longer have a the real filename (the strings "foo" and "foo\n" are two different things because whitespace is significant in filenames; attempting to open the later by giving it the former isn't going to work).

      (And to save everyone who blithely tries my open example above frantic googling or indiscriminate rm invocations, perl -e 'unlink( "foo\n" ) will clean things up :)

      Update: Minor tweaks to wording of 2nd para.

        Fletch, thank you so much for the great explanation and for taking the time to elaborate. I'm still learning perl and this is just plain good info. I don't think the wasted time via the chomp will be an issue because this is a simple system and all the file names are program generated, and in a fixed format, but it's still good to know. Also, I'll fix the 'or' issue right away. Thanks again.