1 Replies - 8881 Views - Last Post: 03 February 2013 - 06:21 AM

#1 rjolitz  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 110
  • Joined: 17-May 08

PERL Arrays

Posted 31 January 2013 - 10:38 PM

Evening All:

I'm trying to figure out how to replace a value in an array without changing it's position IN the array. For this project, I'm reading 10 items from a text file into an array. I have a second array with 10 values of zero.

Based on random number generation, I want to increment the number of items found based on what is found.




sub getitem
	{
		$item_found = rand($itemfound);
		$item_found = $item_found - 1;
		if ($item_found < 0) {
		
			$item_found = $item_found * -1;
			}
			
		print "\n\n************************** $item_found ***********************\n\n";
		print "You have found: $gameitems[$item_found]\n\n";
                menu();




I've gotten this to find and show the random item. But I have no clue how to increment the inventory count by 1 in the second array.

YEs, this means I haven't puzzled out how to manage a multidimensional array in PERL. This is my first attempt using this language.

any pointers or idea to get me in the right direction is welcome.

Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: PERL Arrays

#2 dsherohman  Icon User is offline

  • Perl Parson
  • member icon

Reputation: 226
  • View blog
  • Posts: 654
  • Joined: 29-March 09

Re: PERL Arrays

Posted 03 February 2013 - 06:21 AM

View Postrjolitz, on 01 February 2013 - 06:38 AM, said:

I've gotten this to find and show the random item. But I have no clue how to increment the inventory count by 1 in the second array.

YEs, this means I haven't puzzled out how to manage a multidimensional array in PERL. This is my first attempt using this language.


You need to use the power of... references! (See perldoc perlreftut for all the gory details.)

Perl doesn't do multidimensional arrays as such, it uses arrays of references instead, which provides more flexibility by allowing each "dimension" to be of a completely different sort. In this case, for example, you'd be much better off with an array of hashes rather than an array of arrays, since hashes let you actually name the elements instead of having to remember that 0 is the item's name, 1 is the number in inventory, 2 is the weight...

So, based on your posted code:
sub getitem {
  $item_found = rand(@gameitems);
  $gameitems[$item_found]{inventory_qty}++;

  print "\n\n************************** $item_found ***********************\n\n";
  print "You have found: $gameitems[$item_found]{name}\n\n";
  menu();


I also changed the code for selecting the item so that it gets the number of available items directly based off of the number of items in @gameitems so that you don't need to keep track of how many items are available in $itemfound.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1