Skip to content
Advertisement

Accessing Default directory in perl

I am having a perl script which is taking a directory path as input and then script iterates through all the files present in that directory. For each file it calls some other function.

Here is the script:

JavaScript

My question here is when i am reading input directory, in case if does not exists how can make above script read from “Some Default Directory location”. I tried adding some logic but did not work for me. This is my first perl script so please excuse me if this is too basic to ask.

I am working in LINUX environment.

Advertisement

Answer

The first and most critical mistake you have made is to not use

JavaScript

These two pragmas provide more help than any other two lines of code you could possibly add. Never write Perl code without them.

JavaScript

You do not use either of these modules, so for this code, they are redundant.

JavaScript

This can be written

JavaScript

Because an array in scalar context returns its size.

JavaScript

Unless you really need the precision of readdir, what you most often want is glob(). This code will replace the above code:

JavaScript

It will return the relative path (not the absolute path, as your variable name implies — unless the path argument is absolute). For example: examples/foo.xml.

JavaScript

I assume this sub is just an example, because it does nothing, and can be reduced to a simple print.

As to your question about default directory to read from, that to me is at odds with the requirement of an argument (where you check @ARGV). But you can do a simple check for existence:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement