PerlZealot has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone!!! I want to write a little sub that takes the output from:  system(pwd); and stores it in a variable. Here's my code:
#!/usr/bin/env perl sub dirgets() { my $dirval; system(pwd); $dirval = <STDOUT>; return($dirval); } my $name; $name = &dirgets();
The problem is that I don't seem to get a value from this. Sure, pwd does its thing, but "dirgets" does not. What am I messing up?

Replies are listed 'Best First'.
Re: use of <STDOUT>
by locked_user sundialsvc4 (Abbot) on Mar 06, 2008 at 22:15 UTC

    How about just using back-tick? return `pwd`;

    Since this sort of thing is done so often, the "back-tick" quote-mark causes the enclosing command to be executed and the result returned as a character string. Your entire subroutine becomes ... unnecessary.   :-O

    On my keyboard, this character (along with tilde "~") is located on the upper-left side, to the left of the numeral-"1" key.

    “This is Perl. There is more than one way to do it.™ ”

      And some of the ways don't involve calling an external utility; c.f. Cwd, POSIX (specifically getcwd therein).

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

        I would normally use cwd(). Strangely, when I am running the Perl interpreter that comes with cygwin installation, cwd() never seems to return anything...
Re: use of <STDOUT>
by igelkott (Priest) on Mar 06, 2008 at 22:19 UTC
    Use backticks $dirval = `pwd` or open(P, "pwd |").
Re: use of <STDOUT>
by TGI (Parson) on Mar 06, 2008 at 23:34 UTC

    If you just want the current directory, use core module Cwd.

    use Cwd; print cwd;


    TGI says moo

Re: use of <STDOUT>
by halfcountplus (Hermit) on Mar 07, 2008 at 13:24 UTC
    Don't use system, use open with a pipe (avoiding <STDOUT>):

    #!/usr/bin/perl
    use strict;
    
    my $dir;
    open(SYS, "pwd |");
    while (<SYS>) {$dir=$_; last;}
    chomp $dir; print $dir;
    
    
    Incidentally, if you use my $pid = open(SYS, "pwd |") you get the process number of "pwd" in a variable.

    I presume there is no need to close(SYS) but someone may know better.