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

below is the way creating a file a write. open report_handler, ">", "report.txt"; Can I change the file handle "report_handler" to a variable starting with $?
my $report_handler; open $report_handler, ">", "report.txt";
I tried and seems OK, so why we need the file handle?

Replies are listed 'Best First'.
Re: perl handle and common variable
by aitap (Curate) on Apr 08, 2013 at 07:03 UTC
Re: perl handle and common variable
by dsheroh (Monsignor) on Apr 08, 2013 at 09:48 UTC
    Just to clarify some terminology that it appears you may have misunderstood: At the end of your second bit of posted code, $report_handler is a file handle. A "file handle" is the operating-system level resource used by programs to interact with files (and other file-like things, like pipes, stdin, stdout, etc.).

    The difference you've discovered is the difference between a bareword (or typeglob) file handle (report_handler) and a lexical file handle ($report_handler). Bareword file handles mostly exist for the sake of backwards compatibility these days. Any new code should use lexical file handles instead.

Re: perl handle and common variable
by Anonymous Monk on Apr 08, 2013 at 06:00 UTC

    I tried and seems OK, so why we need the file handle?

    Because you didn't read the documentation for open or perlintro?

Re: perl handle and common variable
by Rahul6990 (Beadle) on Apr 08, 2013 at 06:10 UTC
    File handle is required to perform read and write operation on the underlying file. For accessing the file content you have to go through the file handle. Example: $file = '/etc/passwd'; # Name the file open(INFO, $file); # Open the file @lines = <INFO>; # Read it into an array close(INFO); # Close the file print @lines; # Print the array