Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Perl Programming/Filehandles

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Perl Advanced output Modifiers Reading files Procedural interface By slurping file This method will read the whole file into an array. It will split on the special variable $/ # Create a read-only file handle for foo.txt open (my $fh, '<', 'foo.txt'); # Read the lines into the array @lines my @lines=<$fh>; # Print out the whole array of lines print @lines; By line processing This method will read the file one line at a time. This will keep memory usage down, but the program will have to poll the input stream on each iteration. # Create a read-only file handle for foo.txt open (my $fh, '<', 'foo.txt'); # Iterate over each line, saving the line to the scalar variable $line while (my $line = <$fh>) { # Print out the current line from foo.txt print $line; } Object-oriented interface Using IO::File, you can get a more modern object-oriented interface to a Perl file handle. # Include IO::File that will give you the interface use IO::File; # Create a read-only file handle for foo.txt my $fh = IO::File->new('foo.txt', 'r'); # Iterate over each line, saving the line to the scalar variable $line while (my $line = $fh->getline) { # Print out the current line from foo.txt print $line; } # Include IO::File that will give you the interface use IO::File; # Create a read-only file handle for foo.txt my $fh = IO::File->new('foo.txt', 'r'); my @lines = $fh->getlines; # Print out the current line from foo.txt print @lines; Perl Advanced output Modifiers