APM: Use of the ampersand, "&"

Thomas L. Shinnick tshinnic at io.com
Fri Sep 30 11:40:52 PDT 2005


At 08:41 9/30/2005, don james wrote:
>Hi,
>
>Okay.  I have another question.  Which file handle gets duplicated?
>
>In  the following example:
>
>open(LOG, ">>/foo/logfile");
>and later
>open(STDERR, ">&LOG");
>
>Does "LOG" become the same as "STDERR" or does "STDERR" become the same
>as "LOG"?

Yes, think of it as 'becomes' or "is made the same as this handle already open".

>In other words,  if the system sends messages to STDERR, does that same
>message also get sent to LOG and then to /foo/logfile?

Actually, much closer to "output to STDERR goes to /foo/logfile, and output to LOG goes to /foo/logfile" - no intermediate steps needed.

As Taylor mentioned, this just duplicates/copies the low-level filehandle  and gives it a new Perl-level handle name.  Consider it an new aliased name.

If you have used the command line much you will realize what the docs for open mention, that this exactly parallels usage like:
    tar xvzf foo.tar.gz  >listing 2>&1
where you are doing something much like
    open(STDOUT,'>','listing') or die $!;
    open(STDERR,'>&',STDOUT)   or die $!;
    print "plain print produced\n";
    warn "errors excitedly eeking\n";


>Sincerely,
>
>Don James
>
>Thursday, September 29, 2005Thu, 29 Sep 2005 14:05:52 -050014:05-
>050014:05-0500 at 837ThomasThomas L. Shinnicktshinnic at io.com
>
>>At 12:54 9/29/2005, Taylor Carpenter wrote:
>>>don james wrote:
>>>> She has an example where the "&" precedes a filename.  It is used in the
>>>> following context:
>>>> 
>>>> open(SAVED, ">&STDOUT");
>>>
>>>That is for duping the file handle.  See dup(2) and perldoc -f open.
>>
>>perlfaq5 "How do I dup() a filehandle in Perl?" gives a good example. 
>>You already have a file open, and now you want to re-use that handle when
>>opening another file.
>>    open(LOG, ">>/foo/logfile");
>>and later
>>    open(STDERR, ">&LOG");
>>This allows the second open to be ignorant of what file is being used by
>>the first.  Useful also if you want to force some output to wahtever
>>STDERR points to
>>    open(TRACE, ">&STDERR");
>>without some underlying routine having to know.  Check out Test::Builder
>>where they do open(TESTERR,">&STDERR') to keep a copy of STDERR in case
>>the following code being tested changes where STDERR outputs to.
>>
>>>Taylor




More information about the Austin mailing list