1

I'm still new to perl, so apologies for the rookie question!

I'm using glob to reference the home directory.

The first part of the script names a path to a folder and confirms that it exists:

$path = glob("~/Desktop/Folder/nextFolder/file.txt");
if( !(-e "$path") ) {
    print "Error: invalid path <$path>\n";
    exit 1;
}

Initially I was just using the following script:

$path = "~/Desktop/Folder/nextFolder/file.txt";
if( !(-e "$path") ) {
    print "Error: invalid path <$path>\n";
    exit 1;
}

but it was throwing up the "Error: invalid path" error when executed.

I've read up on glob but I don't really understand it - I found this solution online and tried it, and it worked!

Can someone please explain what it's doing to allow the reference to the home directory? Why doesn't this work without it?

Let me know if this needs more information! Thank you!

Caitlin
  • 93
  • 1
  • 1
  • 8
  • 3
    See [How do I find a user's home directory in Perl?](http://stackoverflow.com/q/1475357/176646) for a more portable approach. – ThisSuitIsBlackNot Feb 02 '16 at 15:59
  • 1
    That's actually where I found the solution in the first place, it's still left me a bit confused... Thank you though @ThisSuitIsBlackNot – Caitlin Feb 02 '16 at 16:02
  • 1
    [File::HomeDir](https://metacpan.org/pod/File::HomeDir) is the portable solution I was referring to. I don't think `glob('~')` works on all platforms. – ThisSuitIsBlackNot Feb 02 '16 at 16:05
  • 1
    Do `($path)=` or you will be using glob as an iterator and it will return undef the second time that line runs – ysth Feb 02 '16 at 16:08
  • 1
    Note that `my $path = glob("...");` is buggy. Put the code in a loop to see the bug. If you just want the first result, use `my ($path) = glob("...");` instead. – ikegami Feb 02 '16 at 16:09
  • 1
    It's the same in the shell. If you escape the `~` to avoid having it treated specially (e.g. `ls -d \~`), the shell will look for a file named `~` (`ls: cannot access ~: No such file or directory`). – ikegami Feb 02 '16 at 16:25

1 Answers1

3

From perldoc -f glob:

In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted.

The ~/ is a shell shorthand that indicates the current user's home directory.

Running it through glob expands ~/ into /home/someuser/ (or wherever the home directory is).

If you don't expand it, then Perl looks for a directory that is actually called ~.

(You only iterate across the list (which is one item long) once).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335