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

后端 未结 3 1591
陌清茗
陌清茗 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.

提交回复
热议问题