random file name in perl generated with unusual characters

344 views Asked by At

Using this perl code below, I try to output some names in a random generated file. But the files are created with weird characters like this:

"snp-list-boo.dwjEUq5Wu^J.txt"

And, obviously when my code looks for these files it says not such file. Also, when I try open the files using "vi", they open like this

vi 'temporary-files/snp-list-boo.dwjEUq5Wu
.txt'

i.e. with a "new line" in the file name. Someone please help me understand and solve this weird issue. Thanks much!

code:

my $tfile = `mktemp boo.XXXXXXXXX`;
my $fh = "";
     foreach my $keys (keys %POS_HASH){
       open ($fh, '>>', "temporary-files/snp-list-$tfile.txt");
        print $fh "$keys $POS_HASH{$keys}\n";
        close $fh;
         }
2

There are 2 answers

0
neuhaus On BEST ANSWER

mktemp returns a line feed character in its output that you need to chop() or chomp() first.

Instead of using the external mktemp program, why don't you go with File::Temp instead?

0
Dave Cross On

Using external programs unnecessarily is a bad idea for a few reasons.

  • The external program that you use might not be available on all of the systems where your code runs. You are therefore making your program less portable.
  • Spawning a new sub-shell to run an external program is a lot slower than just doing the work in your current environment.
  • The values you get back from the external program are likely to have a newline character attached. And you might forget to remove it.

It's the last one that is burning you here. But the others still apply as well.

Perl's standard library has, for many, many years included the File::Temp module which creates temporary files for you without the need to use an external program.

use File::Temp qw/ tempfile /;

# It even opens it and gives you the filehandle.
($fh, $filename) = tempfile();