hello!!

Discussion in 'Perl' started by adroit89, Nov 29, 2007.

  1. adroit89

    adroit89 New Member

    Joined:
    Jan 5, 2007
    Messages:
    24
    Likes Received:
    0
    Trophy Points:
    0
    how to open a text file using perl????
     
  2. naveen

    naveen New Member

    Joined:
    Jun 2, 2005
    Messages:
    39
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Calcutta, India
    Home Page:
    http://naveenhere.blogspot.com
    PHP:
    #!usr/bin/perl

    use strict;

    my $file_name="file.txt";

    open (R$file_name);
    while(<
    R>){
           
             print 
    $_;

    }
    close R;
    The above code opens a file in a READ-ONLY mode and then the while loop iterates through the file and prints every line as it is. You can do whatever operation you want to do within the while loop.

    Alternatively, you can feed the contents of the file into an array by doing

    PHP:
    my @file_contents = <R>; ## Replace the while(){} loop with this code
    and then perform array operations on it.

    You can open a file in Append mode and Write mode by doing

    PHP:
    open (R">>$file_name"); ## For appending to the file
    open (R">file_name"); ## For creating a new file, if it doesn't exist, else delete an existing file and recreate it from blank
    You can also open a file for reading by doing

    PHP:
    open (R"<file_name");
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice