akshay34 has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys I am trying to create a code which checks if the file exists and if it does not, it will glob all the files in the directory and it will append that information to the file that the user specified in the beginning of the script. I have tried many times but the code is not creating a new file and appending the globbed information into it. Please help me figure out my mistakes and give me some pointers.

Here is my code so far:
#!/usr/bin/perl $file = '/home/user/dir'; print "Enter filename to search\n"; chomp ($file = <STDIN>); if (-e $file) { die "File already Exists!\n"; } unless (-e $file) { @appfiles = glob "*"; open(@appfiles, '>>/home/user/dir'); print "List of all the files in the directory:\n"; print "@appfiles\n"; } close(@appfiles);

Thanks for any help in advance

Replies are listed 'Best First'.
Re: Need help appending to a user defined file
by toolic (Bishop) on Sep 19, 2012 at 20:06 UTC
    You want to open a filehandle, not an array of file names. You should print to a file handle, not to STDOUT.
    use warnings; use strict; my $file2 = '/tmp/foo'; print "Enter filename to search\n"; chomp( my $file = <STDIN> ); if ( -e $file ) { die "File already Exists!\n"; } unless ( -e $file ) { my @appfiles = glob "*"; open my $fh, '>>', $file2 or die $!; print $fh "List of all the files in the directory:\n"; print $fh "@appfiles\n"; close $fh; }

    See also the Basic debugging checklist