Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

Embed Size (px)

Citation preview

  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    1/6

    4/29/13 Perl File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open-creating-reading-and-writing-to-files-in-perl/

    1

    Perl File Open: Creating, Reading and Writing to Filesin Perl

    Dealing with files in Perl is very easy once you get used to the slightly odd syntax. Hereare some examples to get you started.

    Open a File in Perl

    To open a file in Perl, just the open() subroutine.

    Heres an example of a program that opens a file, reads the file one line at a time andprints each line to the terminal.

    use strict;use warnings;

    # Put the file name in a string variable# so we can use it both to open the file# and to refer to in an error message# if needed.my $file = "temp.txt";

    # Use the open() function to open the file.unless(open FILE, $file) {

    # Die with error message# if we can't open it.die "\nUnable to open $file\n";

    }

    # Read the file one line at a time.while(my $line = ) {

    # We'll just print the line for now.print $line;

    }

    # close the file.close FILE;

    If you want to read binary files in Perl, you need to set the binmode on the file handle.

    Learn Perl By Doing It

    http://www.caveofprogramming.com/http://www.caveofprogramming.com/http://www.caveofprogramming.com/
  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    2/6

    4/29/13 Perl File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open-creating-reading-and-writing-to-files-in-perl/

    Get the complete course here

    Includes 11 completely free videos nosubscription necessary.

    The following example also illustrates how you can read an entire file in one go. Of courseif the file is large and your memory limited, this might be a bad idea. Usually youprobably want to read a fi le in chunks, writing out the chunks to another file as you go.

    use strict;use warnings;

    # Put the file name in a string variable# so we can use it both to open the file# and to refer to in an error message# if needed.my $file = "temp.bin";

    # Use the open() function to open the file.unless(open FILE, $file) {

    # Die with error message# if we can't open it.die "\nUnable to open $file\n";

    }

    # Tell Perl we want to read data as binary.binmode(FILE);

    # Get rid of the line separator.# This allows us to read everything# in one go.undef $/;

    # Read the entire file. If you don't want# to read all of it at once, you need the# read() subroutine.my $contents = ;

    print "Read " . length($contents) . " bytes\n";

    # close the file.close FILE;

    Read 520 bytes

    If you are dealing with a text file, its often useful to set the file record separator $/ (setto the newline character by default) to some other value, such as a particular closing XMLtag. Undefining it altogether, as in the above example, causes the entire file to be readat once.

    http://www.udemy.com/perltutorial/http://www.udemy.com/perltutorial/
  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    3/6

    4/29/13 Perl File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open-creating-reading-and-writing-to-files-in-perl/

    Creating Files In Perl

    To create a file in Perl, you also use open(). The difference is that you need to prefix thefile name with a > character to make Perl open the file for writing. Any existing file withthe name you supply to open() will be overwritten, unless you specify >> instead, whichopens a file for appending.

    This program creates a file called temp.txt and writes two lines to it.

    use strict;use warnings;

    # Put the file name in a string variable# so we can use it both to open the file# and to refer to in an error message# if needed.my $file = "temp.txt";

    # Use the open() function to create the file.unless(open FILE, '>'.$file) {

    # Die with error message# if we can't open it.

    die "\nUnable to create $file\n";}

    # Write some text to the file.

    print FILE "Hello there\n";print FILE "How are you?\n";

    # close the file.close FILE;

    Open A Text File, Process It and Write to Another File

    Heres a complete example of a program that opens a text file in Perl, reads it line byline, carries out processing on each line and writes the results to another file.

    # Always define these two at the tops of# your scripts.use strict;use warnings;

    # This turns off output buffering.# Useful for real-time display of# progress or error messages.$|=1;

    # This is for getting command-line options.# Could alternatively use @ARGV instead.use Getopt::Std;

    # Return a usage message. Usually we'd indent the# contents of a subroutine, but here we can't since# that would affect the usage message.sub usage {return q|

    usage:process.pl -i -o

  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    4/6

    4/29/13 Perl File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open-creating-reading-and-writing-to-files-in-perl/

    Reads all lines in , changes all occurences of'dog' to 'cat' and writes the results to .

    itself is not changed.

    |;}

    sub main {

    # Collect the -i and -o options from the command line.my %opts;

    # The colons specify that the preceeding flags take# arguments (file names in this case)getopts('i:o:', \%opts);

    # Check we got the flags and arguments we need.unless($opts{'i'} and $opts{'o'}) {

    die usage();}

    # Now we've got the input and output file names.my $input = $opts{'i'};my $output = $opts{'o'};

    # Try to open the input file.unless(open INPUT, $input) {

    die "\nUnable to open '$input'\n";}

    # Try to create the output file# (open it for writing)unless(open OUTPUT, '>'.$output) {

    die "\nUnable to create '$output'\n";}

    # Read one line at a time from the input file# till we've read them all.while(my $line = ) {

    # Change dog to cat$line =~ s/dog/cat/ig;

    # Write the line to the output file.print OUTPUT $line;

    # Print a progress indicator.print '.';

    }

    # Close the files.close INPUT;close OUTPUT;

    }

    main();

    All pages on this site are copyright 2013 John W. Purcell

  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    5/6

    4/29/13 Per l File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open-creating-reading-and-writing-to-files-in-perl/

    1

    Post to Facebook11

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Name *

    Email *

    Website

    Comment

    You may use these HTML tags and attributes:

    Post Comment

    Posted in Perl | Tagged file, perl, programming |

    Home

    Learn Java Swing

    Copyright 2013 John W. PurcellContact

    Close Dialog

    Contact

    Name

    Email

    Like One person likes this.

    http://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.contactme.com/4df20591b15c2d0001010a2d?locale=en&u=http%3A%2F%2Fwww.caveofprogramming.com%2Fperl%2Fperl-file-open-creating-reading-and-writing-to-files-in-perl%2F&f=4df20591b15c2d0001010a2d&ha=left&va=middle&tx=Contact&lb=Contact&c=68202C&vid=13e540d7ab910a20http://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.caveofprogramming.com/http://www.caveofprogramming.com/tag/programming/http://www.caveofprogramming.com/tag/perl-2/http://www.caveofprogramming.com/tag/file/http://www.caveofprogramming.com/category/perl/http://www.shareaholic.com/api/share/?title=Perl+File+Open%3A+Creating%2C+Reading+and+Writing+to+Files+in+Perl&link=http%3A%2F%2Fwww.caveofprogramming.com%2Fperl%2Fperl-file-open-creating-reading-and-writing-to-files-in-perl%2F&notes=&short_link=&shortener=google&shortener_key=&v=1&apitype=1&apikey=8afa39428933be41f8afdb8ea21a495c&source=Shareaholic-Publishers&template=&service=5&ctype=http://www.udemy.com/java-swing-complete/?couponCode=copface
  • 8/22/2019 Perl File Open_ Creating, Reading and Writing to Files in Perl _ Cave of Programming

    6/6

    4/29/13 Perl File Open: Creating, Reading and Writing to Files in Perl | Cave of Programming

    www.caveofprogramming.com/perl/perl-file-open -creating-reading-and-writing-to-files-in-perl/

    Complete video course

    View 7 videoscompletely free

    Nearly all majorwidgets

    Databases

    Design patternsAnimation

    Web Programming:Servlets and JSPs

    Complete video course

    View 7 videoscompletely free

    Create Java web appsLearn JSPs, servletsand JSTL

    Connect to DatabasesDiscover how to

    deploy for free

    http://www.udemy.com/java-swing-complete/?couponCode=copfacehttp://www.udemy.com/javawebtut/?couponCode=copfacehttp://www.udemy.com/java-swing-complete/?couponCode=copface