Programming Fundamentals/Files/Perl

files.pl edit

#!/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.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Perl_Programming

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 edit

Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.

See Also edit