Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > PERL TUTORIALS > USEFUL PERL SCRIPTS WITH REGULAR EXPRESSIONS


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Useful Perl Scripts With Regular Expressions
By Matthew Drouin - 2003-12-18 Page:  1 2 3 4 5 6

Open A File Using Perl

In Perl there are a lot of ways to do the same thing so if you open your files differently then feel free to continue to do so but we need to discuss how to open files for those who are just reading this to quickly get a rather large number of files modified.

open ( FILE, "/home/directory/file.txt" ) or
    die
"Cannot open file: $!";
?>

In the code above we see an example of opening a file located in "/home/directory/file.txt", which is a Unix directory structure. To make this work on a windows machine you just have to put in a windows path like "C:\\my documents\\file.txt". While it might seem funny to see the double slashes they are required because a single slash is put in front of special characters so in order for Perl to read a single slash in a string you need to do double slashes. You could always use a forward slash instead of a black slash too and then you would only need one slash but lets not get confused here.

There is one more type of open that we will want to do and that is an open where we are allowed to then write to the file. While it might seem odd to have to open a file differently when you want to write to it there is a good reason for it. You do not want to open a file that is meant just to be read from and then start writing to it by accident in your code. Since Perl requires you to open the file a little differently as we can see in the code sample below, there will be no chance of us opening a file we only want to read from and then writing to it by accident.

open ( OUTFILE, ">/home/directory/file.txt") or
    die
"Cannot open file: $!";<BR>
?>

As you can see all we did was add a greater than sign (>) in front of the path name to make it so we can write to the file. It is very simple to do but again by leaving out the greater than sign we make it so we cannot write to the file and will probably end up saving ourselves from over writing files that we forgot to backup and will take hours to recreate.

Being that we are good programmers we have to close the file once we are done with it so that we do not run into issues and cause the file to become corrupted. To close the file is simple as can be seen in the code below.

close FILE;
?>


View Useful Perl Scripts With Regular Expressions Discussion

Page:  1 2 3 4 5 6 Next Page: Replace On A Single File

Copyright 2003-2004 Matthew Drouin. All rights reserved.


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.