How to read a file in Perl, and if it does not exist, create it?

In Perl, I know this method:

open( my $in, "<", "inputs.txt" );

reads a file, but it only does so if the file exists.

In other words, with +:

open( my $in, "+>", "inputs.txt" );

writes a file / truncates if it exists, so I do not get the opportunity to read the file and save it in the program.

How to read files in Perl if the file exists or not?

Ok, I edited my code, but the file is not readable. The problem is that it is not in the loop. Anything naughty with my code?

open( my $in, "+>>", "inputs.txt" ) or die "Can't open inputs.txt : $!\n";
while (<$in>) {
    print "Here!";
    my @subjects    = ();
    my %information = ();
    $information{"name"}     = $_;
    $information{"studNum"}  = <$in>;
    $information{"cNum"}     = <$in>;
    $information{"emailAdd"} = <$in>;
    $information{"gwa"}      = <$in>;
    $information{"subjNum"}  = <$in>;
    for ( $i = 0; $i < $information{"subjNum"}; $i++ ) {
        my %subject = ();
        $subject{"courseNum"} = <$in>;
        $subject{"courseUnt"} = <$in>;
        $subject{"courseGrd"} = <$in>;
        push @subjects, \%subject;
    }
    $information{"subj"} = \@subjects;
    push @students, \%information;
}
print "FILE LOADED.\n";
close $in or die "Can't close inputs.txt : $!\n";
+4
source share
3 answers

Use the correct test file file :

use strict;
use warnings;
use autodie;

my $filename = 'inputs.txt';
unless(-e $filename) {
    #Create the file if it doesn't exist
    open my $fc, ">", $filename;
    close $fc;
}

# Work with the file
open my $fh, "<", $filename;
while( my $line = <$fh> ) {
    #...
}
close $fh;

( ), while . , :

if(-e $filename) {
   # Work with the file
   open my $fh, "<", $filename;
   while( my $line = <$fh> ) {
      #...
   }
   close $fh;
}
+7

+>> /, , , :

open(my $in,"+>>","inputs.txt");
+1

First check if the file exists or not. Check out the sample code below:

#!/usr/bin/perl
use strict;
use warnings;
my $InputFile = $ARGV[0];
if ( -e $InputFile ) {
    print "File Exists!";
    open FH, "<$InputFile";
    my @Content = <FH>;
    open OUT, ">outfile.txt";
    print OUT @Content;
    close(FH);
    close(OUT);
} else {
    print "File Do not exists!! Create a new file";
    open OUT, ">$InputFile";
    print OUT "Hello World";
    close(OUT);
}
0
source

All Articles