#!/usr/bin/perl -w #Experimenting with files print "Enter filename:"; chomp($fname = ); ## Open a file. If unsuccessful, print an error message and quit. open (FPTR,$fname) || die "Can't Open File: $fname\n"; # First Technique: "Slurping" # This approach reads the ENTIRE file into memory # Caution... This is not a good method for BIG files!!! @filestuff = ; #Read the file into an array print "The number of lines in this file is ",$#filestuff + 1,"\n"; print @filestuff; close (FPTR); #Close the file ## Some other useful capabilities ## Testing file attributes: print "Enter another filename:"; chomp($fname = ); if (-T $fname) # Check if it's a textfile, and how old { print "File $fname is textfile. "; print "It was modified ", int(-M $fname), " days ago.\n"; open (FPTR,$fname) || die "Sorry. Can't Open File: $fname\n"; } elsif (-B $fname) # Check if it's a binary file, and some other stuff { print "File $fname is executable.\n" if (-x $fname); print "This file is ", -s $fname, " bytes.\n"; die "Since it is Binary file, we will not try to \"upcase\" this file.\n"; } else {die "File $fname is neither text nor binary, so it may not exist. \n" ; } ## Open a file for writing. Note UNIX-like I/O redirection symbol, ">". open (OUTFILE, ">upcase.txt") || die "Can't oupen output file.\n"; ## Better approach for large files... Work with just current input line. while () # While still input lines in the file... { print "1. ",$_; # The symbol "$_" is the default variable, the current # input from file. Note: "$_" is assumed if left out. tr/a-z/A-Z/; # Translate all lower case letters to uppercase letters # in the default variable. print "2. ", $_; s/A/@/g; # More substitutions: All "A" chars become "@" signs. print"3. ", $_; s/UP/Down/g; # All "UP" words are replaced by the string "Down" print "4. ", $_; $pattern = '\sF(.*)L'; # Meaning of Regular Expression: # \sF - starts with a and capital F # .* - some stuff in between # L - Has a capital L in it # The parentheses "mark" the stuff in between print " Match value: ", $1, "\n" if (/$pattern/);; s/$1/*/g if $_ =~ $pattern; # Substitute "*" for the marked pattern, # but anywhere within the line. print "5. ", $_, "\n"; print OUTFILE $_; # Print default variable to OUTFILE. } close (FPTR); # Close the other two files close (OUTFILE);