#!/usr/bin/perl

# To run a perl program on any unix/linux machine or cygwin, just type
# perl filename.  Alternatively, make sure the above #! line points
# to the perl on your machine, do chmod +x filename, then just run
# the filename as an executable.  I never used Perl on windows except
# inside cygwin, so you'll have to figure out how to do that yourself.


# scalar variables


my $x = 2;

print "the value of x is $x \n";

my $y = "adfsfs";

# arrays / lists

my @l = (2,3,5,7,11);

# cons

@l = (0,@l);

print @l , "\n";

print $l[3], "\n"; # prints 5

print $#l, "\n";  # last valid index

# hash tables
my %id;
$id{"fred"} = 700111111;
$id{"ted"} = 700222222;


# n!

sub rf
{
  #   $_[0], $_[1]

    my $n = $_[0];
    if ($_[0]<2) {1} else {$_[0] * rf($_[0]-1)}
}

print rf(4), "\n";

# "return" optional
# {}

sub wf
{   # let = my
    my $n= $_[0];   # my $n=shift;  alternative
    my $ax = 1;
    while ($n > 2)
    {
	$ax = $ax * $n;
        $n--;
    }
    $ax   # ; on last is optional
}

$m = 10;
print wf($m), "\n";

my ($x,$y) = (2,3);
($x,$y) = ($y,$x);

foreach $x (1,2,3,4,5,6,7,8,9,10)
{ print 2**$x, " "; }


# pointers

my $x = 4;
my $px = \$x;  #  int *px = &x;
#  $$px
# member is x in L

sub member
{
    my ($x,@L) = @_;
    my $ax = 0;  # false
    foreach my $y (@L) {if ($y==$x) {$ax=true}}
    return $ax;
}

print member(2,1,3,2,5,7,8), "\n"; # should be true


sub member2
{
    my ($L,$x) = @_;
    my $ax = 0;  # false
    foreach my $y (@$L) {if ($y==$x) {$ax=true}}
    return $ax;
}

@l = (1,2,3,4,5);
print member2(\@l,2), "\n"; # should be true


# pointers to functions

my $fact;
$fact = sub 
{
    my $n = $_[0];
    if ($n<2) {1} else {$n * $fact->($n-1)}   
};

print $fact->(8), "\n";
print &$fact(8), "\n";

# A->B   (*A).B


$pl = \@l;
# accessing array element through a pointer:
$pl->[3];  # $l[3]

