in reply to Usage of File Handles

Yeah, you can either use a positive integer as a file handle, or you can use a text label or you may use a variable name with a dollar sign in front of it, but if you do that, then you have to declare the variable my $INPUT_FILE_HANDLE; before you can use it. Notice, I like to write the < > signs and the file name as one string. That way my Perl script will be backward compatible with older DOS Perl. (I currently use TinyPerl 5.8, but it's neat when I can run the same script in DOS as well.) Also, don't forget to close your opened file handles before the program ends. ;)

#!/usr/bin/perl -w use strict; use warnings; open(INPUT_FILE_HANDLE, '< c:/boot.ini') or die('Cant open file for re +ading'); open(OUTPUT_FILE_HANDLE, '> c:/outfile.txt') or die('Cant open file fo +r writing'); print <INPUT_FILE_HANDLE>; print OUTPUT_FILE_HANDLE "Hello world!!!\n"; close OUTPUT_FILE_HANDLE; close INPUT_FILE_HANDLE;

Replies are listed 'Best First'.
Re^2: Usage of File Handles
by haukex (Archbishop) on Feb 08, 2019 at 06:56 UTC
    Yeah, you can either use a positive integer as a file handle, or you can use a text label

    Note that catfish1116 is using Perl 5.12 or better, in which case lexical filehandles are generally recommended. Also, to pick a nit, it's not a "text label", it's actually a "bareword filehandle", which is essentially a global variable, which is one of the reasons that such filehandles are usually not recommended anymore.

    don't forget to close your opened file handles before the program ends

    Although closing filehandles explicitly as soon as possible is a good idea, the way you've written this implies that Perl doesn't close filehandles automatically, but it does. Another advantage of lexical filehandles is that they are closed automatically as soon as they go out of scope.

    Note that most of this has been discussed before. Lexical filehandles were introduced in Perl 5.6, so they are available even in your TinyPerl 5.6 and 5.8.