Programming Fundamentals/Files/Perl: Difference between revisions
Jump to navigation
Jump to search
Content deleted Content added
Creating |
(No difference)
|
Revision as of 22:48, 3 March 2017
files.pl
#!/usr/bin/perl
# This program creates a file, adds data to the file, displays the file,
# appends more data to the file, displays the file, and then deletes the file.
# It will not run if the file already exists.
sub create_file
{
my ($filename) = @_;
open my $file, '>', $filename;
print {$file} "C\tF\n";
for ($c = 0 ; $c <= 50 ; $c += 1)
{
$f = $c * 9.0 / 5 + 32;
print {$file} $c . "\t" . $f, "\n";
}
close $file
}
sub read_file
{
my ($filename) = @_;
open my $file, '<', $filename;
while(my $line = <$file>)
{
print $line;
}
close $file;
print "\n";
}
sub append_file
{
my ($filename) = @_;
open my $file, '>>', $filename;
for ($c = 51 ; $c <= 100 ; $c += 1)
{
$f = $c * 9.0 / 5 + 32;
print {$file} $c . "\t" . $f, "\n";
}
close $file
}
sub delete_file
{
my ($filename) = @_;
unlink($filename);
}
sub main
{
my $FILENAME = "~file.txt";
if (-e $FILENAME)
{
print "File already exists.\n";
}
else
{
create_file($FILENAME);
read_file($FILENAME);
append_file($FILENAME);
read_file($FILENAME);
delete_file($FILENAME);
}
}
main()
Try It
Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.