0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perlを使いWindowsのホームディレクトリにフォルダを作ろうとしてハマった点

Posted at

はじめに

make_dir_in_home_dir.pl
use strict;
use warnings;

mkdir "~/dir_name";

と書いたら、ホームディレクトリにdir_nameフォルダができるような気がしました。

しかし、うまくいきませんでした。

正解

Windowsではこのようにする必要があります。

make_dir_in_home_dir.pl
use File::Path 'mkpath';

chomp(my $home_dir = `echo %homepath%`);
mkpath "$home_dir/dir_name";
command
$ perl make_dir_in_home_dir.pl
$ ls ~
dir_name

mkpathとは、複数階層のディレクトリを一度に作ってくれる便利なやつです。

参考ページ: 複数階層のディレクトリを作成する File::Path::mkpath() - Perlゼミ

原因は不明

Bash on Ubuntu on Windows上やPowerShell上で、最初のスクリプトを実行してもうまくいきませんでした。
それどころか、カレントディレクトリにもホームディレクトリにも作ろうとしたディレクトリは現れませんでした。

そもそもmkdir "~/dir_name";は使えないようです。

スクリプトの実行自体にエラーはないのですが、dir_nameディレクトリがどこに行ったのかは謎のままです。

$ENV{HOME}は使えなかった

最初は環境変数として$ENV{HOME}を使おうと試みましたが、中身が空っぽでした。

print_home_dir.pl
use warnings;

print "Home directory is $ENV{HOME}?\n";
コマンドプロンプト
$ perl print_home_dir.pl
Use of uninitialized value $ENV{"HOME"} in concatenation (.) or string at test.pl line 3.
Home directory is ?

下記の参考ページのコメント欄2つ目を見ると、取れないとのことです。

Windowsの環境変数はいくつかあって、%ENVでアクセスできるのは、
http://www.atmarkit.co.jp/fwin2k/win2ktips/460envset/envset.html
の環境変数の種類の説明でいうプロセス環境変数なので、システム環境変数やユーザー環境変数とは別物です。

参考ページ: 【Perl】【Windows】システム環境変数を取得できますか? Active… - 人力検索はてな

これに関してBash on Ubuntu on Windowsでは動作したため、その環境であれば使えます。

おわりに

これだからWindowsってやつは!

でも好きです。

もし何か気づいたこと、気になったことがあれば教えてください!
あと、もう少し簡単な方法はないのでしょうか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?