[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Multidimensional array question



As Chris said (sort of).

The "#" after the "$" is used to denote the last location within
an array.  You can cycle through an entire array by either using the
"@" or create a loop using the "$#" variable.

example:

	for( $i=0; $i<=$#myArray; $i++ ){
		print $myArray[$i], "\n";
		}

is the same as:

	print @myArray;

except that the second statement assumes that there is a carriage return
at the end of each entry in the array.

The "$#" variable (which is named the same thing as the array itself) is
a very useful tool for manipulating an array.  Let's say you want to
read in a bunch of lines from a file into an array.  You can yank
everything in by doing the following:

	open( THEFILE, "myFile.dat" ) || die $!;
	@myArray = <THEFILE>;
	close( THEFILE );

or you can do this:

	@myArray = ();
	open( THEFILE, "myFile.dat" ) || die $!;
	while( <THEFILE> ){
		$myArray[++$#myArray] = $_;
		}

	close( THEFILE );

Now, you are probably wondering why you'd ever use the second method
when the first one is so much faster.  The answer has to do with what
you want to do with the information once you got it.  If, after reading
a line of data you want to massage the information and then place it
into an array, the second method would be easier to use.

The last really neat thing about the "$#" variable is that it is so
useful when dealing with arrays.  You don't need to keep an additional
variable around just to know how many entries there are in an array. 
There always are just "$#X" number of entries.

Now the drawback:  So far as I know, multidimensional arrays do not
contain a "$#" variable for anything other than the first entry of an
array.  Thus:

	$myArray[$#myArray][$#subScript1][$#subScript2]

do not exist.  Chris?  Paul?  Matthias?  Am I wrong about this?  If so -
let me know too.  :-)

PS: To Matthias: I found the video where you say hello.  Very nice! 
Hello to you too!  :-)

--------------------------------------------------------------------------------
All e-mail needs to be sent to mark@cheers.jsc.nasa.gov.  If you don't,
it will
probably bounce.  What man does not understand or fears; he ultimately
destroys.
Steve Wright: Black holes are where God divided by zero.

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch