0% found this document useful (0 votes)
5 views4 pages

Perl File Handling and Data Manipulation

This document contains Perl code examples for performing various file input/output operations: 1. The first example writes a simple string to a text file. 2. The second example takes user input from standard input and writes it to a file. 3. Additional examples demonstrate reading and printing a file's contents, using a hash to associate names with families, reversing the keys and values of a hash, counting word frequencies, and formatting environment variables in columns.

Uploaded by

Roopesh Jhurani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Perl File Handling and Data Manipulation

This document contains Perl code examples for performing various file input/output operations: 1. The first example writes a simple string to a text file. 2. The second example takes user input from standard input and writes it to a file. 3. Additional examples demonstrate reading and printing a file's contents, using a hash to associate names with families, reversing the keys and values of a hash, counting word frequencies, and formatting environment variables in columns.

Uploaded by

Roopesh Jhurani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Perl Programs RJ

1. Writing to files with perl this program writes using file handler to
[Link] file but text is given inside program itself. Next program
uses <stdin>
Greater than operator wipes out old file if present with same name and
creates one.
If warnings were not use then if file location would not have been
presented correct say in some directory dir/[Link] then too script would
not have told [Link] would have just keep on running..so use warnings
always. So even if file is not available done will get printed.

use strict;
use warnings;
my $filename = '[Link]';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "My first report generated by perl\n";
close $fh;
print "done\n";
2. use strict;
use warnings;
my $filename ='[Link]';
open(my $fh, '>', $filename) or die "'$filename' $!";
#print $fh "my second report by perl\n";
print $fh <stdin>;
close $fh;
print "done\n";
Now this program uses stdin so it will take through stdin user from
input and will print to $fh i.e., using this handler it will print it to file
associated to with, so now any input can be taken from user.
This die thing is to stop script in between if file required is not found.
[Link] - all taken from this link.
Short and simple file operations: [Link]

3. Program to print file content on screen


use warnings;
open $fh, '<', '[Link]' or die "not able to open $!";
while($line=<$fh>)
{
print $line;
}
close $fh;
4. Program to prepare a hash key value and print while
continuously getting input from user.
$family_name{'fred'}='ran';
$family_name{'janny'}='roy';
$family_name{'raven'}='ravi';
print "enter family name\n";
while(chomp(my $name=<stdin>))
{
print "I have met $name $family_name{$name} \n";
}
If @arr=%family_name;
Print @arr; then this will print the keys and values of the key value
hash pair in an array form..no guarantee that they will in the same
order.
5. Code to change key,value,key,value in an array from hash pair
to
Value,key,value,key and so on. And also presented is a
goodway to include hash pairs.
my %family_name = (
'fred' => 'flintstone',
'dino' => undef,
'barney' => 'rubble',
'betty' => 'johny',
);
@arr=%family_name;
print "@arr\n";
my %inverse_hash=reverse %family_name;
@reverse=%inverse_hash;

print "@reverse\n";
can omit keys quotes but say an operator is used as key so
confusion so better keep it.
Also remember for comparsion something..first chomp the
value.
6. Code to enter word count using hash trick.
print "enter words\n";
while(chomp(my $word=<stdin>)){
if(exists $count{$word}){
$count{$word}+=1;
}
else
{
$count{$word}=1;
}
}
foreach my $key(sort keys %count)#see keys is a system keyword in
#perl
{
$value=$count{$key};
print "$key=>$value\n";
}
7. Program to print all the environment variables in column
format with length used of maximum key as the column width.
my $longest = 0;
foreach my $key ( keys %ENV ) {
my $key_length = length( $key );
$longest = $key_length if $key_length > $longest;
}
foreach my $key ( sort keys %ENV ) {
printf "%-${longest}s %s\n", $key, $ENV{$key};
}
8. A program to match a particular string in a program but with
case sensitivity but this program gives it even with an
attachment with a big word.. so here we find fred. Now this
program it even coming if given input say Alfred. But not
coming from Fred.
Idea is to open a filehandle to get the text from file and similar
to how we display it on the screen we take it in file handle and

play with it. So here dont think of printing $line or $fh


everything comes inside $_.
text
>cat test_file10.txt
1. hello fred how are you
2. hello Fred how are you
3. hello fredrick how are you
4. helllo alfred
5. hello everyone out there
6. hello all
program displays only lines with small fred so lines 1,3,4 get
printed.
use warnings;
open $fh, '<', 'test_file10.txt';
while(<$fh>)
{
if(/fred/)
{
print $_;
}
}
close $fh;
if u want to include Fred aswell then change it to/[fF]red/ or /(f|F)red/ or /fred|Fred/

Common questions

Powered by AI

To modify a Perl program for case-insensitive search of the string 'fred', you can use a regular expression that includes both lowercase and uppercase options. This can be achieved using patterns like /[fF]red/ or /(f|F)red/ included in the while loop condition when reading the file lines. This ensures the program matches 'fred' regardless of capitalization .

A hash can be utilized to count word occurrences by using the words as keys and their frequencies as values. As each word is input through <stdin>, the script checks if the word already exists in the hash using the 'exists' function. If it exists, it increments the count; otherwise, it initializes the count to one. This method is efficient because hash lookups and updates are generally O(1), providing rapid aggregation of input data without needing to traverse or sort the data collection repeatedly .

When printing key-value pairs from a Perl hash as an array, the pairs are naturally unordered due to the inherent nature of hashes. To print them in a specific order, one should sort the keys first. This can be done using the 'sort keys' function which enables sorting by key values. It ensures that each output pair is consistently printed according to a predictable sequence, e.g., lexicographical order .

Reversing a hash in Perl involves rearranging the key-value pairs so that values become keys and keys become values. This can be accomplished using the 'reverse' function. It's important to ensure that values are unique, as duplicates would result in data loss during inversion. Even with unique values, the reversed order of keys and values may not retain any original sequence due to the unordered nature of hashes, so any desired sorting must be applied after reversal .

In Perl, input and output redirection are managed using filehandles that act as a bridge between Perl scripts and the data sources or destinations (e.g., files or standard input/output). By opening a filehandle with specific modes ('<', '>', '>>'), one can read from or write to files. This mode flexibility facilitates precise control over whether data is fetched or pushed, and whether files are overwritten, appended to, or simply read. Filehandles thus provide essential flexibility for dynamically managing data streams .

Hashes in Perl offer a dynamic means of storing and retrieving key-value pairs, crucial for text processing where associative array behavior is required. They allow for rapid look-up, insertion, and deletion of data. In tasks such as word counting, hashes enable tracking of occurrences efficiently by storing words as keys and their counts as values. This capability is particularly valuable in dynamically managing data, accommodating changes and updates seamlessly without restructuring the entire dataset .

In Perl, the '<' operator redirects input from a file, allowing the script to read data, while the '>' operator directs output to a file, overwriting existing content. The implications for data integrity are significant: using '>', any pre-existing data is erased, ensuring the output file's contents fully reflect the script's latest execution rather than appending to old data. This makes the use of '>' suitable for applications needing fresh outputs per execution .

Not using 'use warnings' in Perl file operations can lead to silent failures, especially if a file location is incorrectly specified. Without warnings, the script does not alert the programmer about the non-existence or inaccessibility of the required file. It would continue executing as if everything were normal, which could lead to incorrect program outcomes or data loss. Warnings serve as an essential debugging aid by promoting cautionary alerts that prompt programmers to address potential issues with file paths and operations .

Robust exception handling in Perl file operations is achieved through strategic use of 'die' and 'warn' statements. These functions allow for immediate termination or issuance of warnings when critical errors occur, such as failing to open a file. Surrounding file operations with these functions ensures that the code responds appropriately to errors, preventing unpredictable behaviors or data corruption by alerting the programmer immediately and, thus, halting faulty execution paths early .

Formatting output to align environment variables involves initially determining the longest key length and using it as the column width. This is calculated by iterating over all keys in the %ENV hash to compare and track the maximum length. Then, the 'printf' function is used in a subsequent loop to print each key and its value, with the key formatted to a width specified by the longest length calculated, ensuring a neat column alignment .

You might also like