drum drum - 1 year ago 71
Perl Question

How to get first file in directory by alphabetical order?

I want to execute

$filename = `ls *.gz | head -n 1`;
through perl but I think the pipe is causing an error.
Execution of -e aborted due to compilation errors.

This will be part of the perl script rather than run via

What would be the correct way to do this?

Answer Source

How about

my $filename = (sort glob "*.gz")[0];

You state the alphabeticall order thus the sort, which by default uses the "standard string comparison order" (see docs). Note that ls can be aliased, while its defaults also may depend on the system.

Going out to the shell would make sense only if you were to use some particular strengths of ls, that would take a lot of work to do in Perl. For mere sorting there is no reason to go out of your program. It is far less efficient and adds a whole list of new problems to solve.

A good point was raised by mob. Because of the invokation sort BLOCK|SUB LIST one could wonder whether glob could be taken in an unintended way. It's not, as that function runs first. However, this may well be just clearer

my ($filename) = sort (glob "*.gz"); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download