[comp.lang.perl] How do I create new filehandles?

jand@kuling.UUCP (Jan Dj{rv) (07/18/90)

I want to make a sub which opens a file and returns a filehandle.

Here's my naive solution:

sub new_file {
        local($file) = @_;

        open(F, "> $file") || die "Can't open $file\n";
        return *F;
}

(The real application is a bit more involved...:-).

However, this doesn't work, since perl uses the same fd for F in all calls
to new_file.

*FIRST = &new_file('file_one');
print fileno(FIRST), "\n";
*SECOND = &new_file('file_two');
print fileno(SECOND), "\n";
exit 0;

gives prints 3 two times. What is the proper way to do this?

And now for something completly different...


With perl PL 18:
% perl -e 'print time;'
648311529% 
% perl -e 'print time, "\n";'
No comma allowed after filehandle at /tmp/perl-ea01682 line 1.
% perl -e 'print "", time, "\n";'
648311550 
%

The same thing seems to happens for any print statement that has a builtin
with no arguments as its first argument.
Like in
perl -e '$_ = 3.141;print cos, "\n";'
perl -e 'print eof, "\n";'

and so on.

A bug surely?


	Jan D.

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (07/21/90)

In article <1593@kuling.UUCP> jand@kuling.UUCP (Jan Dj{rv) writes:
: I want to make a sub which opens a file and returns a filehandle.
: 
: Here's my naive solution:
: 
: sub new_file {
:         local($file) = @_;
: 
:         open(F, "> $file") || die "Can't open $file\n";
:         return *F;
: }
: 
: (The real application is a bit more involved...:-).
: 
: However, this doesn't work, since perl uses the same fd for F in all calls
: to new_file.
: 
: *FIRST = &new_file('file_one');
: print fileno(FIRST), "\n";
: *SECOND = &new_file('file_two');
: print fileno(SECOND), "\n";
: exit 0;
: 
: gives prints 3 two times. What is the proper way to do this?

package newfile;
$fh = 'fh00';
sub main'new_file {
        local($file) = @_;
	$fh++;

        open($fh, "> $file") || die "Can't open $file\n";
        return $fh;
}

package main;
$FIRST = &new_file('file_one');
print fileno($FIRST), "\n";
$SECOND = &new_file('file_two');
print fileno($SECOND), "\n";
exit 0;

: With perl PL 18:
: % perl -e 'print time;'
: 648311529% 
: % perl -e 'print time, "\n";'
: No comma allowed after filehandle at /tmp/perl-ea01682 line 1.
: % perl -e 'print "", time, "\n";'
: 648311550 
: %
: 
: The same thing seems to happens for any print statement that has a builtin
: with no arguments as its first argument.
: Like in
: perl -e '$_ = 3.141;print cos, "\n";'
: perl -e 'print eof, "\n";'
: 
: and so on.
: 
: A bug surely?

Yes.

Larry