[ ^ CSE 341 | section index | <-- previous | next -->]

Input and Output

Input and output in Perl happens (primarily) through filehandles, which vaguely resemble FILE * in C. Filehandles are not declared like other variables; they are created using the open call and have no special punctuation:

open( HANDLE, "<filename" ) or die "Could not open file: $!"; # Use angle bracket operator to read a line $line = <HANDLE>; # All open filehandles should be closed close( HANDLE );

Passing handles between subroutines, and having them work fully the way you expect, usually involves horrible hacks. Here is some voodoo that happens to work:

sub copy_line { my ($in, $out) = @_; my $line = <$in>; print $out $line; } open( IN, "<file1" ) or die "Error: $!"; open( OUT, ">file2" ) or die "Error: $!"; copy_line(IN, OUT); close( IN ); close( OUT );

If you don't want to just read one line at a time, there are library functions that give you more flexibility:

# Character by character I/O my $char = getc( HANDLE ); # Read specified number of bytes read( HANDLE, $bytes, 100 );

Last modified: Wed Apr 12 19:09:19 PDT 2000