Use Use My My Die Print: Strict Warnings $filename Open $FH $filename or $FH Close $FH
Use Use My My Die Print: Strict Warnings $filename Open $FH $filename or $FH Close $FH
1. Writing to files with perl this program writes using file handler to
report.txt 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/file.txt then too script would
not have told us.it 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 = 'report.txt';
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 ='report.txt';
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.
http://perlmaven.com/writing-to-files-with-perl - all taken from this link.
Short and simple file operations: http://www.thegeekstuff.com/2010/09/perlfile-handle/
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