#!/usr/bin/perl

use strict;


main();

sub main {


    #foreach loops operate on arrays(or Refs to arrays).
    #foreach loops make one loop for each element in an array.


    print "\nPrint out the value of each element in an array and test if it starts with the letter \'a\'\n\n";

    #our array of 4 elements
    my @array = ('12','superfudge','apple','orange');

    #eac value is read from the @array and assigned to $value.
    #this continues until all of the elements are read from the array
    #the original array is not changed!
    foreach my $value (@array) {

	#we capture the first character of  the current element of the array
	# we are dealing with
	my $first_char = substr($value,0,1);
	
	#we initialize the variable which holds the results of our test 
	my $starts_with_a = undef;

	#carry out the test
	if ($first_char eq "a") {
	    $starts_with_a = "true";
	} else {
	    $starts_with_a = "false";
	}

	print "\t\'$value\' starts with a\?  $starts_with_a\n";
	
    }
    print "\n\nnow we'll play with a foreach loop and a hash reference\n\n####################\n";

##foreach loops can also operate on the return values of operations when they return arrays.... forexample, to iterate through all of the key/value pairs in a hash..

    
    my %some_hash->{"red"} = "rum";
    %some_hash->{'happy'} = "days";
    %some_hash->{'12'} = "twelve";
    %some_hash->{'three'} = "3";

    foreach my $key (keys(%some_hash)) {
	print "\tKey: $key .. Value: $some_hash{$key}\n";
    }

    print "\n\nnotice the order is not in the order i set the values... if you want to sort by keys you can add the \'sort\' operation\n";

    
    foreach my $key (sort(keys(%some_hash))) {
	print "\tKey: $key .. Value: $some_hash{$key}\n";
    }
    
    ##WArning.. the sort operation can behave badly sometimes... read the docs if you have problems with it...

    print "\n\nOr maybe reverse sort the keys?\n\n";


    foreach my $key (reverse(sort(keys(%some_hash)))) {
	print "\tKey: $key .. Value: $some_hash{$key}\n";
    }
    print "\n";
}

