#!/usr/bin/perl -w use strict; my($dif,$whichstock,$howmany,$goal,$date,$cash,$trans); #Always name hashes for the value stored in them my (%stock_price, %holding); my %half_spread= ( derpco => 10, tetrabytz => 40, mojoinc => 20, freke => 25, mega => 35, ); foreach (keys %half_spread) { $stock_price{$_}=gen_rand(10, 100); $holding{$_}=0; } print "What Goal In Cash Do You Want To Set? :"; chomp ($goal=); #Check user input for sanity die "Your goal has to be a number.\n" unless $goal=~/\d+/; print "Thanks\n\n"; $date=1; $cash=100; until ($cash > $goal or $date == 31) { $date=$date+1; foreach (keys %stock_price) { my $hs = $half_spread{$_}; $stock_price{$_}+=gen_rand(1-$hs, $hs); do{$stock_price{$_} = 0; $holding{$_}=0} if $stock_price{$_} <1; } check_date($date); if (gen_rand(0,50) == 5) { print "there is a small market error in your favor!\n\n"; $whichstock=(keys %holding)[gen_rand(0,scalar((keys %holding)))]; $howmany=gen_rand(1,10); $holding{$whichstock}=$holding{$whichstock}+$howmany; } print "\n\nYour Stock Report for January $date\n\n"; print "Company You Own Value\n"; foreach (keys %holding) { print "$_ $holding{$_} \$$stock_price{$_}\n"; } print " you have \$$cash\n"; print "Would you like to (B)uy or (S)ell? "; $trans=; if ($trans =~/S/i) { sell(); }; if ($trans =~/B/i) { buy(); } } #I prefer sub declarations at the end. Pure personal preference #Use _ to separate words in sub names sub gen_rand { my $startNumber = shift(); my $endNumber = shift(); my $randNumber = int($startNumber + rand() * ($endNumber - $startNumber)); return $randNumber; }; sub sell { print "What Stock would you like to Sell? "; my $sell; chomp ($sell=); if ( $sell=any($sell, keys %holding)) { print "\nyou have $holding{$sell} stocks in $sell\n"; print "Sell How many? :"; my $sellnum; chomp ($sellnum=); if ($sellnum > $holding{$sell} or $sellnum == 0) { print "Nice try, but you could get arrested for tricks like that.\n" } else { $holding{$sell}-=$sellnum; $cash+=$sellnum*$stock_price{$sell}; }; } } sub buy { print "What Stock would you like to buy? "; my $buy; chomp ($buy=); if ( $buy=any($buy, keys %holding)) { print "\nyou have $holding{$buy} stocks in $buy and \$$cash\n"; print "buy How many? :"; my $buynum; chomp ($buynum=); if ($cash < $stock_price{$buy}*$buynum) { print "Not enough cash\n" } else { $holding{$buy}+=$buynum; $cash-=($buynum*$stock_price{$buy}) } } } sub any { my $search_name = shift; my @search_list = @_; foreach (@search_list) { return $_ if ( /$search_name/i ) ; } return undef; } sub check_date { my $date = shift; if ($date == 30) {print "Last Day!! better sell your stock"}; if ($date > 30) { if ($cash > $goal) { $dif = $cash-$goal; print "Yay! you won, you beat your goal by \$$dif\n"; exit; }; if ($cash < $goal) { $dif = $goal-$cash; print "Boo! you lost, you missed your goal by \$$dif\n"; exit; }; } }