Why does my Perl script fail on “~/” but works with “$ENV{HOME}”?

后端 未结 3 1590
陌清茗
陌清茗 2021-01-26 22:47

I have been using this script of mine FOREVER and I have always been using \"~/\" to expand my home directory. I get into work today and it stopped working:

#if          


        
相关标签:
3条回答
  • 2021-01-26 23:05

    As stated by prior answer, "~" (tilde) is expanded by shell, not perl. Most likely, it was working due to existence of a directory "~" in your current directory, which eventually got removed, leading to the bug surfacing:

    To illustrate:

    1. Tilde not working in Perl, using $ENV{HOME} works:

      $ echo MM > MM
      $ perl5.8 -e '{print `cat ~/MM`}'
      cat: cannot open ~/MM
      $ perl5.8 -e '{print `cat $ENV{HOME}/MM`}'
      MM
      
    2. Making the tilde-named directory works:

      $ mkdir \~
      $ echo MM > \~/MM
      $ ls -l \~
      -rw-rw-r--   1 DVK users          3 Jun 10 15:15 MM
      $ perl5.8 -e '{print `cat ~/MM`}'         
      MM
      
    3. Removing it restores the error, as you observed:

      $ /bin/rm -r \~
      $ ls -l \~
      ~: No such file or directory
      $ perl5.8 -e '{print `cat ~/MM`}'
      cat: cannot open ~/MM
      

    This offers a plausible explanation, though I'm not 100% there can't be others.

    0 讨论(0)
  • 2021-01-26 23:06

    The tilde expansion is not done by perl, it is done by the shell.

    You should instead use:

     use File::Spec::Functions qw( catfile );
     ...
     my $fn = catfile $ENV{HOME}, 'tmp', "find_$strings[0].rslt";
     ...
     open my $out, '>', $fn or die "Cannot open '$fn': $!";
    
    0 讨论(0)
  • 2021-01-26 23:20

    ~ is expanded by the shell. Perl has no idea about it. So, it would work only within a shell script.

    0 讨论(0)
提交回复
热议问题