Pearl text scripts


Perl script example --> Read a file

#!/usr/local/bin/perl
#filehandle called MYFILE, open it and point it to data.txt file
#while loop -- read read one by one the lines of the file and places the value of each line to the temporary variable $_ for one loop.
#chomp function to clear off the new lines from the end of each line
#print the value of $_
#close the handle
 open (MYFILE, 'data.txt');
 while (<MYFILE>) {
  print "$_\n";
  chomp;
 }
 close (MYFILE);

Perl script example --> Write a file

#!/usr/local/bin/perl
#file is opened in append mode via the prefix symbol >>
#to overwrite an existing file with a new one, the > prefix should be used
#print to a filehandle -- print statement with the filehandle
#close the filehandle to finish the program
 open (MYFILE, '>>data.txt');
 print MYFILE "Bob\n";
 close (MYFILE);

Parsing text files example


#!/usr/bin/perl
#read a line
#chomp any whitespace
#assign a group of three different variables
#split function to break the line on the tab character --> \t
#variables are printed separately

 open (FILE, 'data.txt');
 while (<FILE>) {
 chomp;
 ($name, $email, $phone) = split("\t");
 print "Name: $name\n";
 print "Email: $email\n";
 print "Phone: $phone\n";
 print "---------\n";
 }
 close (FILE);
 exit;

Multiple text parsing and writing
while statement, diamond <> operator and $ARGV variable

#!/usr/bin/perl
#The while loop repeats the execution of a block as long as a certain condition is 
evaluated true

use strict; # Always!
use warnings; # Always!

my $header = 1; # Flag to tell us to print the header
while (<>) { #operator value should be empty
    if ($header) {
        # This is the first line, print the name of the file
        print "========= $ARGV ========\n";
        # reset the flag to a false value
        undef $header;
    }
    # Print out what we just read in
    print;
}
continue { # This happens before the next iteration of the loop
    # Check if we finished the previous file
    $header = 1 if eof;
}

------------------------------------------------------------------------------------

No comments:

Post a Comment


Free online chess

View Kapellas Nick's profile on LinkedIn
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License