Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

It seems like FILEHANDLER is more commonly used as a handler naming convention than $filehandler. But it can give a bareword error if one forgets to use *FILEHANDLER in some constructions.

What are advantages and disadvantages of HANDLERS and $handlers?

Which naming convention is a better practise, and why?

share|improve this question
    
In this case it's "handle", not "handler". –  Andrew Medico Jan 23 at 5:37
    
recommended reading: Why is asking a question on “best practice” a bad thing? –  gnat Feb 13 at 5:24

2 Answers 2

up vote 12 down vote accepted

It is better to use $filehandler because your filehandles will be lexically scoped. It means you won't accidentally sabotage or clash with another filehandle. You'll get a warning if you try to declare another variable with the same name. This format was introduced in Perl 5.6 so it is a newer format.

Bareword filehandles are global names. You could overwrite an existing filehandle with the same name without knowing it. It could cause some confusion if you have a constant or subroutine with the same name. And you probably won't get any warnings if you do have any of these clashes.

btw, this is one of the items listed in Perl Best Practices by Damian Conway. It's also better to use the 3-arg form of open: open my $fh, '<', $file.

share|improve this answer

I assume you're talking about using a FileHandle object versus a namespace/bareword or glob?

  1. Using FileHandle gives you an object. If your surrounding code is OO, it makes sense. It also makes it more readable as to when it is in scope, and how it is used. See IO::Handle

  2. Perldoc http://perldoc.perl.org/perlop.html#I%2fO-Operators

  3. I agree with stevenl, <>

  4. If you're using -w or use strict; there are issues with BAREWORDS. Safer to have a reference.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.