| |
perl: copy file snippet
copy file snippet
perl: copy file snippet
There may cases where you need to read a file only a few characters at a time instead of line-by-line. This may be the case for binary data. To do just that you can use the read command.
read a file only a few characters at a time instead of line-by-line -------------------------------------------------------- open (FILE, "picture.jpg") or die $!; binmode FILE; my ($buf, $data, $n); while (($n = read FILE, $data, 4) != 0) { print "$n bytes read\n"; $buf.= $data; } close(FILE); ------------------------------------------------------- There is a lot going on here so let's take it step by step. In the first line of the above code fragment a file is opened. As you can guess from the filename it is a binary file. Binary files need to treated differently than text files on some operating systems (eg, Windows). The reason is that on these platforms a newline "character" is actually represented within text files by the two character sequence \cM\cJ (that's control-M, control-J). When reading the text file Perl will convert the \cM\cJ sequence into a single \n newline characted. The converse also holds when writing files. Clearly, when reading binary data this behavior is undesired and calling binmode on the filehandle will make sure that this conversion is avoided. ------------------------------------------------------- sub copy { # copy("/folder1/abc.dat", "/folder2/abc.dat") or die("cannot copy\b"); my($from, $to) = @_; if(open(IN, $from)) { if(open(OUT, ">$to")) { binmode(OUT); while(read IN, $buf, 4096) { print OUT $buf; } close IN; close OUT; return 1; } close IN; } return 0; } ------------------------------------------------------- in the first three lines are opened input "$from" and output "$to" file upon that are REPETEDLY red 4096 characters WHILE the reading operation is not completed in each reading loop the previusly red buffer $buf is copied-printed to OUT file the loop is terminated when we read final 4096 characters
|
|