Programming Wiki: Reading Information From a File and into a Variable

Programming Wiki : PerlReadFromFile

WikiHomePage :: Categories :: PageIndex :: RecentChanges :: RecentlyCommented :: Login/Register

Reading Information From a File and into a Variable

Perl


Reading a whole file in at once
open(FILE,"my_file_name");
my @my_array = <FILE>;
close FILE;


Here's a program that reads a file and prints it in sorted order
open(MYINPUTFILE, "<filename.out"); # open for input
my(@lines) = <MYINPUTFILE>; # read file into list
@lines = sort(@lines); # sort the list
my($line);
foreach $line (@lines) # loop thru list
 {
 print "$line"; # print in sort order
 }
close(MYINPUTFILE);


Reading a file line by line
open(MYINPUTFILE, "<filename.out");
while(<MYINPUTFILE>)
 {
 # Good practice to store $_ value because
 # subsequent operations may change it.
 my($line) = $_;

 # Good practice to always strip the trailing
 # newline from the line.
 chomp($line);

 # Convert the line to upper case.
 $line =~ tr/[a-z]/[A-Z]/;

 # Print the line to the screen and add a newline
 print "$line\n";
 }

There are no comments on this page. [Add comment]

Powered by Wikka Wakka Wiki 1.1.6.0
Page was generated in 0.0172 seconds