Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

What is a multidimensional array and how do I use one

by Hopeless (Initiate)
on Oct 30, 2001 at 19:16 UTC ( #122091=perlquestion: print w/replies, xml ) Need Help??
Hopeless has asked for the wisdom of the Perl Monks concerning the following question:

First off, I woudl just like to say Thank You to everyone here, you guys are great and my life would be much more difficult without this site!!! Now on to my question: Can someone explain what a multidimensional array is and how I would go about creating one that will work???
  • Comment on What is a multidimensional array and how do I use one

Replies are listed 'Best First'.
Re: A little help please
by arhuman (Vicar) on Oct 30, 2001 at 19:22 UTC
    'perldoc perl' would have probably pointed you to perllol...
    You could also see the Array sub-section of the monastery's Q&A corner.
    (hint: How do i create array of arrays )

    But if you have a more specific question I'd be glad to answer...

    "Only Bad Coders Code Badly In Perl" (OBC2BIP)
      Well lets see, I currently have 3 loops and I am creating a fourth and I am trying to figure out a way to access the info from the previous 3 loops, and nothing seems to work, it doesn't help that I have been hacking at this script for the past 2 weeks and I really hate it right now. Oh did I mention that I don't know what I am doing either:>

        Show what you've got. Then we'll be able to work out what you don't understand and tailor our replies appropriately.


        "The first rule of Perl club is you don't talk about Perl club."

        So, show us the code you have so far. We're bound to be able to help with a specific example.

        Charles K. Clarkson
(jeffa) Re: What is a multidimensional array and how do I use one
by jeffa (Bishop) on Oct 30, 2001 at 22:11 UTC
    As an additional insight into multidimensional arrays, consider the selectall_arrayref() method from DBI. It returns a reference to a list of references that are lists - or more sustinctly, a 2-Dimensional Array.

    I use this method all the time at work, and dealing with 2-D arrays is a snap. The general rule is, for each dimension, you will need one for loop to iterate through the elements.

    Let's say that you have just issued a database call and have the data stored in a reference. To make it easy, let's pretend that this bit of code is really that database call:

    my $db_results = [ [qw(one two three)], [qw(four five six)], [qw(seven eight nine)], ];
    $db_results is really a 2-Dimensional array, each list points to a list (or list of lists: LoL). Now, here is a cool way to use this data:
    print "<table>\n"; foreach my $row (@$db_results) { print "\t<tr>\n"; foreach my $col (@$row) { print "\t\t<td>$col</td>\n"; } print "\t</tr>\n"; } print "</table>\n";
    This yeilds a nice HTML table:
    <table> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>four</td> <td>five</td> <td>six</td> </tr> <tr> <td>seven</td> <td>eight</td> <td>nine</td> </tr> </table>
    As you can see, arrays and loops go hand in hand. Two array, two loops - three arrays, three loops. Four starts getting hairly, and five is right out! Sorry, MP joke. :)


      BTW, here's a little shortcut, using Instead of this:

      print "<table>\n"; foreach my $row (@$db_results) { print "\t<tr>\n"; foreach my $col (@$row) { print "\t\t<td>$col</td>\n"; } print "\t</tr>\n"; } print "</table>\n";

      Try this:

      # note that passing an array reference to Tr() creates a set of <TR> b +locks, one per element of the referenced array print table( Tr( [ map { td( $_ ) } @$db_results ] ) );

      Or, if you don't like the entire table stretched out into one long line of HTML, this:

      # need '*table' and '*Tr' in order to use start_table() and start_Tr() use CGI qw( :standard *table *Tr ); # ... # note the map() calls each represent a nested for() loop # and further that passing an array reference to td() creates a set of + <TD> blocks, one per element of the referenced array print join( "\n", start_table, start_Tr, (map { map { td($_) } @$_ } @$db_results), end_Tr, end_table ), "\n";

      Sorry ... couldn't help "improving" on your code :)


      You can give a man a fish and feed him for a day ...
      Or, you can teach him to fish and feed him for a lifetime
Re: A little help please
by doc (Scribe) on Oct 30, 2001 at 19:59 UTC

    You have been pointed to the docs, here is a little example. Could I recommend New Monks to you as your title is not very helpful.

    use Data::Dumper; my @array; my @other_array = qw ( First Last Email ); my @yet_another_array = qw ( Perl Monks ); push @array, \@other_array; push @array, \@yet_another_array; push @array, [ 'Perl', 'Hacker', '' ]; # now pick out the 3rd field of the second record. print $array[1][2],"\n"; print Dumper(@array);
Re: A little help please
by Hopeless (Initiate) on Oct 30, 2001 at 20:20 UTC
    Not very pretty:
    use Time::local; my $view = "cmtools_view"; my $ccdrive = $ENV{CC_DEFAULT_DRIVE}; my $file = "$ccdrive\\$view\\swf\\vobadmin\\vob_manager_mrrd.txt"; my $upsitesynckey = "SyncState ERLH"; my $downsitesynckey = "SyncState SCR"; my $upsitereplicakey = "Replica for ERLH"; my $downsitereplicakey = "Replica for SCR"; my @newtime; my $htmlpath='synccheck1.htm'; my $logfile='synccheck.log'; my $maxtime; my %month = (Jan => 0, Feb => 1, Mar => 2, Apr => 3, May => 4, Jun => 5, Jul => 6, Aug => 7, Sep => 8, Oct => 9, Nov => 10, Dec => 11); #Define some colors... my $GRN="#00FF00"; my $YEL="#FFFF00"; my $RED="#FF0000"; my $GRY="#808080"; my $curcolor=$GRN; my %rephash; my $x; my $y; my @erlh; my @scr; open(TFILE2,">$htmlpath") || die "Can't open $htmlpath"; # Print the html header section. print TFILE2 <<WEB_PAGE; <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-12 +52"> <title>SyncCheck</title> </head> <body background="PrairieWind.bmp" bgcolor="#000000" text="#FFFFFF" li +nk="#FFFF00" vlink="#FFFF00"> <p>&nbsp;</p> <p align="center"><font face="Americana" size="5">Clearcase Sync Check + Summary</font></p> <p align="center"><font face="Americana" size="5"></font></p> <p align="left">&nbsp;</p> WEB_PAGE # Handle the "Last Update" my $time=localtime(time); print TFILE2 "<p align=\"center\"><font face=\"Americana\" size=\"4\"> +Last update: $time</font></p><br>\n"; open (FILE, "$file") || die "Can't open $file"; $tmp=<FILE>; foreach(split(/\t/,$tmp)){ push(@vobhashkeys, $_); } while (<FILE>) { $tmp=$_; @vobconfig=split(/\t/,$tmp); $idx=0; #Combine the two arrays into a hash. Taking the long way around, h +ere. foreach(@vobconfig){ $vobhash{$vobhashkeys[$idx]}=$_; $idx++; } #Clear out the arrays. @vobconfig=(""); # Get a more accurate vob tag. $vobname=$vobhash{"VOB-Tag"}; #If the syncstate of a site has an X or "EXPORT", Add its replica +to the list. if(uc($vobhash{$upsitesynckey}) eq "X" || uc($vobhash{$upsitesynck +ey}) eq "EXPORT"){ push(@replicas, $vobhash{$upsitereplicakey}); push +(@vobs, $vobname); } if(uc($vobhash{$downsitesynckey}) eq "X" || uc($vobhash{$downsites +ynckey}) eq "EXPORT"){ push(@replicas, $vobhash{$downsitereplicakey}) +; push(@vobs, $vobname); } %vobhash = (""); } close (FILE); foreach $replica (@replicas) { if ($replica =~ /scr/g || $replica =~ /princeton/g) { push (@scr, $replica); #print TFILE2 "<td><font color=\"$curcolor \">$replica</td>"; #print TFILE2 "<td><font color=\"$curcolor \">$durhours</td>"; } if ($replica =~ /erlh/g) { push (@erlh, $replica); #print TFILE2 "<td><font color=\"$curcolor\"> $replica &nb +sp; </td>"; #print TFILE2 "<td><font color=\"$curcolor\"> $durhours &nbsp +; </td>"; } } $idx=0; foreach $replica (@scr || @erlh) { $cmd="cleartool describe replica:$replica\@\\$vobs[$idx]"; $time=`$cmd`; $time =~ /last_export = /g; $time=substr($time, pos($time), length($time)-pos($time)); @timelocal = localtime(time); $day=substr($time, 0, 2); $mon=substr($time, 3, 3); $year="20".substr($time, 7, 2); $hour=substr($time, 10, 2); $min=substr($time, 13, 2); $sec=substr($time, 16, 2); # Convert the month abbreviation to a number (0-11). Use separate +variable. $mon = $month{$mon}; @newtime=($sec, $min, $hour, $day, $mon, $year, undef, undef, unde +f); $x=Time::Local::timelocal(@timelocal); $y=Time::Local::timelocal(@newtime); $z=$x-$y; my $durhours=int($z/3600); $z-=($durhours*3600); my $durmins=int($z/60); $z-=($durmins*60); my $dursecs=$z; if ($durhours < 3) { $curcolor = "$GRN"; } if ($durhours >= 3 && $durhours < 7 ) { $curcolor = "$YEL"; } if ($durhours > 7 ) { $curcolor = "$RED"; } if ($durhours > $maxtime) { $maxtime = $durhours; } if ($maxtime < 3) { $currentstatus = "OK"; } if ($maxtime >= 3 && $maxtime < 7 ) { $currentstatus = "WARN"; } if ($maxtime > 7 ) { $currentstatus = "ERROR"; } $idx++; } $idxa=0; print TFILE2 "<table width=\"75%\" border=\"1\">"; while ($idx > @scr || $idx > @erlh) { print TFILE2 " <tr>"; print TFILE2 "<td><font color=\"$curcolor \">$scr[$idx]</td>"; print TFILE2 "<td><font color=\"$curcolor \">$durhours</td>"; print TFILE2 "<td><font color=\"$curcolor\"> $erlh[$idx]</td>"; print TFILE2 "<td><font color=\"$curcolor\"> $durhours</td>"; print TFILE2 "</tr>"; print TFILE2 "</tr>"; $idxa++; } print TFILE2 "</table>"; &loghandler ($currentstatus); print "$currentstatus\n"; sub loghandler{ #Updates the log file with the current status. Adds hi +story line to page. my @logs; #Array to hold log entries my @currenttime; my $entryidx; #Index to the correct log entry. my $currentstatus=$_[0]; #Define some colors... my $GRN="#00FF00"; my $YEL="#FFFF00"; my $RED="#FF0000"; my $GRY="#808080"; my $curcolor=$GRN; # Get the log file open(LOGFILE,"$logfile") || die "Can't get $logfile"; $tmp=<LOGFILE>; #Ignore the first line. while(<LOGFILE>){ $tmp=$_; chomp($tmp); push(@logs, $tmp); } close(LOGFILE); # Calculate which entry to change and do it. @currenttime=localtime(time); $entryidx=($currenttime[2]*4)+int($currenttime[1]/15); $logs[$entryidx]=$currentstatus; #Add the timeline to the webpage. print TFILE2 "<p align=\"center\"><font color=\"#FFFF00\">History</p>< +font color=\"#FFFFFF\">\n"; print TFILE2 "<p align=\"center\"><pre>12A 1A 2A 3A 4A 5A 6A 7A + 8A 9A 10A 11A 12P 1P 2P 3P 4P 5P 6P 7P 8P 9P 10P 11P <br> +"; print TFILE2 "<p align=\"center\"><pre>| ' | ' | ' | ' | ' | ' | ' | ' + | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' | ' <br> +"; print TFILE2 "<p align=\"center\"><pre><font color=\"$curcolor\">"; #Re-generate the log file and add entries to the time line. open(LOGFILE,">$logfile") || die "Can't create $logfile"; print LOGFILE "$rgyerror errors in Clearcase registry. \n"; $x=0; foreach $entry (@logs) { if($x > $entryidx){ #RE-Define some colors... $GRN="#00A000"; $YEL="#A0A000"; $RED="#A00000"; $GRY="#808080"; } print LOGFILE "$entry\n"; if($entry eq "OK" && $curcolor ne $GRN){ print TFILE2 "<font color +=\"$GRN\">"; $curcolor=$GRN;} if($entry eq "WARN" && $curcolor ne $YEL){ print TFILE2 "<font col +or=\"$YEL\">"; $curcolor=$YEL;} if($entry eq "ERROR" && $curcolor ne $RED){ print TFILE2 "<font co +lor=\"$RED\">"; $curcolor=$RED;} if($entry eq "UNAVAILABLE" && $curcolor ne $GRY){ print TFILE2 "<f +ont color=\"$GRY\">"; $curcolor=$GRY;} print TFILE2 "*"; $x++; } close(LOGFILE); #Finally add the pointer to the current entry print TFILE2 "<p align=\"center\"><pre><font color=\"#FFFFFF\">"; for(0..$entryidx-1){print TFILE2 " ";} print TFILE2 "^ <br>"; print "Time: $currenttime[2]: $currenttime[1] Entry: $entryidx\n" ; } #End of Sub
      Thank You,

      Can you give me an idea of what 'vob_manager_mrrd.txt' looks like?

      Have you seen the Multidimensional Arrays Tutorial?

      Charles K. Clarkson
        it is a file in notepad that just has a listing of column headings then in the rows there is either a "X" or "Export", I have the code searching for the "X" or "EXPORT" and once it finds it it spits it back at me so I can then use the values.
      What was the intent of the following?
      foreach $replica (@scr || @erlh) {

      Did you perhaps want:
      foreach $replica (@scr, @erlh) {

      thus, stepping through each array?

      Charles K. Clarkson
        yes I think that's it, thank you and to all who posted, I think tha ti have finally figured this out, you guys all rock!!!!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://122091]
Approved by root
and the pool shimmers...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2017-01-24 01:57 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (200 votes). Check out past polls.