#!/usr/bin/perl -Tw

#++
# 
# 
#--

use CGI':standard';
use strict;
$\ = "\n";


# assume we're running in CGI mode if ...
# ... the SERVER_PORT environment variable is set and 80
# (80 is the usual HTTP post)
print header('text/plain') if "80" eq $ENV{SERVER_PORT};

my $variable = 4;

print "Variables are passed to subroutines by value:";
  print "  in main, before call to subroutine(): variable is $variable";
  print "  in main, calling: subroutine(\$variable)";
  subroutine($variable);
  print "  in main, after call to subroutine():  variable is $variable";
  print "";
  print "  in main, calling: subroutine(2+2)";
  subroutine(2+2);
  print "";
  print "  in main, calling: subroutine(1 + \$variable + 1)";
  subroutine(1 + $variable + 1);

print "\nCall by reference can be simulated using references:";
  print "  in main, before call to sub2(): \$variable is $variable";
  print "  in main, calling: sub2(\\\$variable)";
  sub2(\$variable);
  print "  in main, after call to sub2():  \$variable is $variable";


print take_home_message();

# -- subroutines follow -- #

sub subroutine {
    my ($variable) = (@_);  # could also be written as ...
                            # ... my $variable    = $_[0];

    print "    at start of subroutine: my (\$variable) = (\@_)";
    print "    at start of subroutine: \$variable is $variable";
    $variable  = (($variable  + 3) * 2) + 1;
    print "    at end of subroutine:   \$variable is $variable";
} # subroutine()


sub sub2 {
    my ($reference) = (@_);

    print "    at start of sub2: my (\$reference) = (\@_)";
    print "    at start of sub2: \$\$reference is $$reference";
    $$reference  = (($$reference + 3) * 2) + 1;
    print "    at end of sub2:   \$\$reference is $$reference";
} # sub2()


sub take_home_message {
    my $block;
    ($block = <<'  OEN') =~ s/^[ \t]+ ([^ \t])/$1/gmx;
      
      In Summary:
      ~~~~~~~~~~~
      Variables passed to subroutines in perl are passed by value.
      That is copies of the values are passed, not aliases to the variables.
      
      To simulate call by reference (in which aliases are used) we must use
      references.  We can pass a reference (e.g. \$variable) to a subroutine
      by value and then change the value of the variable pointed to through
      the reference.

      For more information about perl's subroutines see the perlsub
      documentation.

      Perl documentation is available online from 
	         * borg         type perldoc perlsub at the command prompt
	         * perldoc.com  <http://www.perldoc.com/perl5.6.1/pod/perlsub.html>
	         * etc.
  OEN
;

  return $block;
} # take_home_message()
