#!/usr/bin/perl

use strict;
use warnings;

#
# Question 1: how does this subroutine stuff work?
#
#
#

my $x_coord = 4.2;
my $y_coord = 3.6;
my $r = radius( $x_coord, $y_coord );
print " x = $x_coord, y = $y_coord, radius = $r \n";

# Usage: $radius = radius($x, $y);
sub radius {
  # The variable @_ is filled with ($x, $y) from caller.
  my ($x, $y) = @_;
  my $answer = sqrt( $x * $x + $y * $y );
  return $answer;
}

#
# Question 2: how about if x, y have many numbers ?
#

my $x_pts = [ 1.2,  2.3,  4.5  ];   # $x_pts is a reference to an array
my $y_pts = [ -2.3, -1.0, -0.2 ];
my @r_pts = radius_array( $x_pts, $y_pts );
for (my $i=0; $i < @$x_pts; $i++){
  print " x = " , $x_pts->[$i], 
        ", y = ", $y_pts->[$i], 
	", r is ", $r_pts[$i], "\n";
}

# Usage: $radius = radius($x, $y);
sub radius_array {
  # The variable @_ is filled with ($x, $y) from caller.
  my ($xref, $yref) = @_;
  my @x = @$xref;
  my @y = @$yref;
  ## debugging:
  # print " array x = '@x' \n";
  # print " array y = '@y' \n";
  # exit;
  my @radii;
  while (@x){
    my $xx = pop @x;
    my $yy = pop @y;
    push @radii, sqrt( $xx**2 + $yy**2 );
  }
  return @radii;
}

#
# Question 3: 
# What's the difference between @_ and $_ ?
#

#   $_ is "it" in perl.  
#   

print();

my @array = 1..100;
print "hi \n" for 1..10;

my @array = (1,10,100,200);

#
# This is a for loop with the structure " for (array){ statemetn } "
#
for (@array){
  print " $_ \n";
}

# Same thing, a bit clearer

for my $i (@array){
  print " $i \n";
}

#
# This is a for loop with the structure "  statement for array "
#

print " $_ \n" for @array;

print for 'a'..'z';

my $sentence = "Hi.  My name is Jim";
for ($sentence){
  s/Jim/Joe/;
  s/Hi/Hello/;
  print;
}

#
# subroutine to swap two values
#
#
my $x = 10;
my $y = 20;
print "\n";
print " (x,y) is ($x,$y) \n";
swap($x, $y);
print " (x,y) is ($x,$y) \n";
# now x is 20, y is 10

sub swap {
  # @_ is (10, 20) when this is called.
  ($_[0], $_[1]) = ($_[1], $_[0]);
}


# @foo  then $foo[0] is the leftmost element of that array.
# $foo is completely different.
