Here are some Perl examples that involves file I/O operations.
Example 1: Given a file srcfile, copy its contents to destfile line-by-line.
Logic:
- Open srcfile for reading and destfile for writing using open command.
- Use a while loop to access each line of srcfile using the file pointer.
- Chomp function is used to remove newline character from the row.
- Print the row to destfile.
- Finally, close the files.
Perl Code:
open ($fileread, '<', 'srcfile') or die $!; open ($filewrite, '>', 'destfile') or die $!; while ($row = <$fileread>) { chomp $row; print {$filewrite} "$row\n"; } close $filewrite; close $fileread;
Example 2: Given a file srcfile, append each line with the pattern #new and paste in a file destfile.
Logic:
This will also be similar to the previous code. However, only change is instead of writing the same line to destfile, we substitute the line with line #new.
Perl Code:
open ($fileread, '<', 'srcfile') or die $!; open ($filewrite, '>', 'destfile') or die $!; while ($row = <$fileread>) { chomp $row; $row =~ s/$row/$row #new/g; print {$filewrite} "$row\n"; } close $filewrite; close $fileread;
Note: Thus, you should be able to manipulate any data from a srcfile and write to the destfile.
Example 3: Given a file srcfile, append each line with the pattern #new in the same srcfile.
Logic:
This is a little trickier to achieve because we cannot perform substitution directly to the same file at different locations. We can only append data.
So we will go for the Linux command sed to achieve this.
sed command format: sed -i Line number s/'pattern to replace'/'new pattern'/ filename
There are many options that can be used with sed which can be explored here: sed Examples
Also note, I have used Perl special variable $. which gives the line number of the current file pointer.
Note that shell commands are enclosed within backticks ` `
Perl Code:
open ($fileread, '<', 'srcfile') or die $!; open ($filewrite, '>', 'destfile') or die $!; while ($row = <$fileread>) { chomp $row; `sed -i $.s/'$row'/'$row #new'/ srcfile`; }
Note: Thus, you should be able to manipulate data in the srcfile itself.
No comments:
Post a Comment