<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>UseStrict Consulting &#187; file and directory manipulation</title>
	<atom:link href="http://usestrict.net/tag/file-and-directory-manipulation/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Sat, 12 May 2012 14:25:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Perl Crash Course: File and Directory Tests and Manipulation</title>
		<link>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/</link>
		<comments>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 15:15:55 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[file and directory manipulation]]></category>
		<category><![CDATA[perl crash course]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=429</guid>
		<description><![CDATA[Basics on manipulating files and directories with Perl.]]></description>
			<content:encoded><![CDATA[<p><strong>by André Batosti<br />
revision: Vinny alves</strong><br />
<code><br />
</code></p>
<h3>Opening Files</h3>
<p>To read or write files in Perl, you need to open a filehandle. Filehandles in Perl are yet another kind of identifier.<br />
They act as convenient references (handles, if you will) between your program and the operating system about a particular file. They contain information about how the file was opened and how far along you are in reading (or writing) the file. They also contain user-definable attributes about how the file is to be read or written.</p>
<p>To open a new file on system you need to create the <em>filehandle</em> for this file using the command open</p>
<p>	<em><strong>open(filehandle, pathname);</strong></em></p>
<p>The filehandle is the identifier that will describe the file and the pathname &#8211; the full path of the file you trying to open. Typically it is represented by a constant, but when working with complex programs, it is best to use a scalar variable in order to safely pass it from one subroutine or method to another.</p>
<p><span id="more-429"></span></p>
<p>Example:</p>
<pre name="code" class="php">
	open(PASS_FILE, "/etc/passwd"); # equivalent to open(PASS_FILE,"&lt; /etc/passwd");
	# or
	open(my $pass_file, "/etc/passwd");
</pre>
<p><strong>Note:</strong> it&#8217;s always a good idea to test if <tt>open()</tt> worked well:</p>
<pre name="code" class="php">
	open(PASS_FILE,"/etc/passwd") || die("Can't open passwd: $!n"); # $! gives the system error message
</pre>
<p>Any modern version of Perl also accepts the 3 parameter notion, which is safer:</p>
<pre name="code" class="php">
	open(PASS_FILE, "&lt;" , "/etc/passwd");
</pre>
<p>When you done all with the file you need to close then using the command close</p>
<pre name="code" class="php">
        close(PASS_FILE);
</pre>
<h3>Reading Files</h3>
<p>You can read from Perl&#8217;s filehandles in a couple of different ways. The most common method is to use the file input operator, also called the angle (or diamond) operator (&lt;&gt;). To read a filehandle, simply put the filehandle name inside the angle operator and assign the value to a variable:</p>
<pre name="code" class="php">
	open(MYFILE, "myfile");
	$line = &lt;MYFILE&gt;;
</pre>
<p>The angle operator in a scalar context reads one line of input from the file. When called after the entire file has been read, the angle operator returns the value undef.</p>
<p>In array context, the whole file is read and stored in the array &#8211; one line per element;</p>
<h3>Writing Files</h3>
<p>To write data into a file you need to open the filehandle to write. The open command before is for reading only. To open for writing we need to use &#8216;&gt;&#8217; mode to create a new file or overwrite an existing one and &#8216;&gt;&gt;&#8217; mode to append an existing file or create a new one.</p>
<pre name="code" class="php">
	open(NEWFILE, "&gt;newfile"); # overwrites or creates newfile
	open(MYFILE, "&gt;&gt;myfile"); # appends data to myfile
</pre>
<p>After open a file to write you can use the print command with the filehandle:</p>
<pre name="code" class="php">
	print NEWFILE "this goes into newfilen"; # note the lack of commas between print and filehandle
</pre>
<h3>More on Modes</h3>
<p>So far we&#8217;ve seen modes &#8216;&lt;&#8217;, &#8216;&gt;&#8217;, and &#8216;&gt;&gt;&#8217;. There are other modes we can use depending on our needs. Adding a &#8216;+&#8217; before &#8216;&gt;&#8217; or &#8216;&lt;&#8217; (making &#8216;+&gt;&#8217; or &#8216;+&lt;&#8217;) will grant us read AND write access to the file. &#8216;+&gt;&#8217;, however, will truncate your file first.</p>
<p>Perl also allows you to use pipes on your filenames, print to anonymous temporary files, and much much more.<br />
See <a href="http://perldoc.perl.org/functions/open.html" target="_blank">perldoc&#8217;s open</a> for more details.<br />
<code><br />
</code>	</p>
<h3>Special filehandles</h3>
<p>The Perl have some special filehandles that was always open this is for standard input, output and error<br />
They are</p>
<ul>
<li>STDOUT &#8211; The standard output</li>
<li>STDIN &#8211; The standart input</li>
<li>STDERR &#8211; The error standard output</li>
</ul>
<p>You can specify which is your default output handle (the one print sends data to when no filehandle is passed) with<br />
the <tt>select()</tt> function:</p>
<pre name="code" class="php">
	open(FH,"&gt; myfile.txt);
	$old_fh = select(FH); # changes default output and saves original
	print "This goes to myfile.txtn";
	close(FH);
	select($old_fh);
	print "This goes to the screenn";
</pre>
<p><code><br />
</code></p>
<p><code><br />
</code>	</p>
<h3>File test operators</h3>
<p>Before you open a file, sometimes it&#8217;s nice to know whether the file exists, whether the file is really a directory, or whether opening the file will give a permission denied error. If you could examine the file&#8217;s metadata, you could get answers to these questions. For these situations, Perl provides the file test operators. The file test operators all have the following syntax</p>
<p><strong><em>-X filehandle</em></strong></p>
<p>OR</p>
<p><strong><em>-X pathname</em></strong></p>
<p>The valid operators for file tests are:</p>
<ul>
<li><em>-r</em> Returns true if the file is readable</li>
<li><em>-w</em> Returns true if the file is writeable</li>
<li><em>-e</em> Returns true if the file exists</li>
<li><em>-z</em> Returns true if the file exists but is empty</li>
<li><em>-s</em> Returns size of the file in bytes if it exists</li>
<li><em>-f </em>Returns true if the file is a regular file rather than a directory</li>
<li><em>-d</em> Returns true if the file is a directory</li>
<li><em>-T</em> Returns true if the file appears to be a text file</li>
<li><em>-B</em> Returns true if the file appears to be a binary file</li>
<li><em>-M</em> Returns the age (in days) since the file was modified</li>
</ul>
<h3>Working with directories</h3>
<p>The first step in obtaining directory information from your system is to create a directory handle. A directory handle is something like a filehandle, except that instead of a file&#8217;s contents, you read the contents of a directory through the directory handle. To open a directory handle, you use the <tt>opendir()</tt> function:</p>
<pre name="code" class="php">
        opendir(dirhandle, pathname);
</pre>
<p>To get the content of the directory you need to use the <tt>readdir()</tt> function to get the next directory entry or the entire list of files, depending on context (scalar or list, respectively). It returns undef once you reach the end of your list.</p>
<pre name="code" class="php">
	$next_file = readdir(dirhandle);
       # OR
	@files = readdir(dirhandle);
</pre>
<p>After you finish you need to close the directory using the function <tt>closedir()</tt></p>
<pre name="code" class="php">
	closedir(dirhandle);
</pre>
<p>A shortcut to this process is to use file globbing techniques:</p>
<pre name="code" class="php">
	@all_files = &lt;*&gt;; # gets you the listing of all files in the current directory
	@shell_scripts = glob("*.sh"); # safer
</pre>
<h3>Basic directory operations</h3>
<p>If you need to change, create and remove directories you can use the functions <tt>chdir()</tt>, <tt>mkdir</tt> and <tt>rmdir</tt> using this syntax:</p>
<pre name="code" class="php">
	chdir pathname; # to change remote dir
	mkdir pathname; # to create a directory
	rmdir pathname; # to remove the entire directory
</pre>
<h3>Basic file operations</h3>
<p>To remove files you need to use the <tt>unlink()</tt> function and to rename, use <tt>rename()</tt> <img src='http://usestrict.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="php">
	unlink list_of_files;
	rename oldname, newname;
</pre>
<h3>The <tt>stat</tt> Function</h3>
<p>If you need to get all information about a file you need to use the <tt>stat()</tt> function.</p>
<p>It returns an array containing the following:</p>
<pre>
0 dev     Device number
1 ino     Inode number
2 mode    File's mode (permissions)
3 nlink   Number of links
4 uid     User ID (UID) of the owner
5 gid     Group ID (GID) of the owner
6 rdev    Special file info
7 size    Size of file in bytes
8 atime   Time of last access
9 mtime   Time of last modification
10 ctime  Inode change time
11 blksz  Disk block size
12 blocks Number of blocks in file
</pre>
<pre name="code" class="php">
        ($dev,  $ino,   $mode,  $nlink, $uid,     $gid,   $rdev,
         $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat(pathname);
</pre>
<p style="text-align:right;"><a href="http://usestrict.net/2009/03/24/perl-crash-course-subroutines/">« Subroutines</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | Some built-in functions for everyday use »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/04/perl-crash-course-file-and-directory-tests-and-manipulation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

