Default directory access in perl

I have a perl script that takes a directory path as input, and then the script iterates over all the files in that directory. For each file, it calls a different function.

Here is the script:

#!/usr/bin/perl

use JSON;   
use XML::Simple;
use File::Spec;

$num_args = $#ARGV + 1;
if ($num_args != 1) {
    print "\nUsage: $0 <input directory>\n";
    exit;
}

my $dir = $ARGV[0];

opendir(DIR, $dir) or die "cannot open directory";

@docs = grep(/\.xml$/,readdir(DIR));

foreach $file (@docs) 
{
    my $abs_path = join("",$dir,$file);
    #print $abs_path;
    my $return_object = some_function_call($abs_path);
    print_output($return_object);
 }

 sub print_output
 {
    my $output_object = $_[0];
    print $output_object;
 }

My question here is when I read the input directory, in case it does not exist, how can the above script be read from "Some Default Directory location". I tried to add some logic, but did not work for me. This is my first perl script, so please excuse me if it is too easy to ask.

I work in a LINUX environment.

+1
source share
3 answers

, , -

use strict;
use warnings;

, , . Perl- .

use JSON;   
use XML::Simple;
use File::Spec;

, .

$num_args = $#ARGV + 1;
if ($num_args != 1) {
    print "\nUsage: $0 <input directory>\n";
    exit;
}

if (@ARGV != 1) {
    print ...
    exit;
}

.

opendir(DIR, $dir) or die "cannot open directory";
@docs = grep(/\.xml$/,readdir(DIR));
foreach $file (@docs) {
    my $abs_path = join("",$dir,$file);

readdir, , , glob(). :

my @docs = glob "$dir/*.xml";

( , ), path ). : examples/foo.xml.

sub print_output {
    my $output_object = $_[0];
    print $output_object;
}

, sub , print.

, , ( @ARGV). :

if (not -e $dir) {
    $dir = "default";
}
+5

constant :

....
use constant DEFAULT_DIR => '/path/to/default/dir';
....

my $dir = $ARGV[0];
$dir = DEFAULT_DIR unless -e $dir;
....

( , : , , dirhandles, , $#array ..)

+2

opendir(DIR, $dir) or die "cannot open directory"; , , $dir :

$default_dir = "....";

if (!-e $dir)
{
    $dir = $default_dir;
}
+1

All Articles