# practical uses of dynamic scoping in Perl

sub f()  # function that refers to external variable STDOUT
{
    print "My password is xyzzy. ";   # STDOUT is by default
    print STDOUT "keep it secret.  Don't save it to a file";
}

sub g()  # use dynamic scoping to temporarily change STDOUT:
{
   open(fileout,">file1.txt");  # open for writing (use >> for append)   
   local *STDOUT = fileout;
   f();
}

# Simulating dynamic scoping using static scoping: can do it in other languages
sub gsim
{
   my $stackstdout = STDOUT;  # save original value of STDOUT
   
   open(outfd,">file2.txt");  # open for writing (use >> for append)
   *STDOUT = outfd;
   f();

   *STDOUT = stackstdout;     # restore original value of STDOUT
}


g();
gsim();  #same effect
