in reply to mkdir in loop - overwrite danger?

A bit more Perlish:

#!/bin/perl use strict; use warnings; use File::Path qw(make_path); my $txt = "txt"; my @files = glob("*$txt"); foreach my $filename (@files) { my ($seq, $nr, $mol, $dir, $step, $type) = (split /[._]/, $filename)[1..6]; print "name of file: $filename \n\n"; make_path("~/folder1/$mol/$dir"); }

Update: corrected typo (thanks poj!). Updated again to use glob instead of ls.

Dum Spiro Spero

Replies are listed 'Best First'.
Re^2: mkdir in loop - overwrite danger?
by afoken (Chancellor) on Dec 22, 2015 at 22:36 UTC
    A bit more Perlish:
    my $txt = "txt"; my @files = `ls *$txt`;

    No need to spawn ls and hope that the shell does not ruin everything. glob can do that in pure perl:

    my $txt='txt'; my @files=glob "*$txt";

    Another way for this simple case (no subdirectories) would be a combination of opendir, readdir, closedir, and grep:

    my $txt='txt'; opendir my $d,'.' or die "Can't opendir .: $!"; my @files=grep /\Q$txt\E$/,readdir $d; closedir $d;

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

      I did consider that, but got lazy; replacing ls with glob meant also having to split off the basename of the file from the path. I liked the simplicity.

      Update: having looked at this again, I see glob returning file names only if that path is not included. That makes for a more portable solution.

      But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)