x
Solved

Populating and Printing Perl 2D arrays.

Posted on 2004-08-19
Medium Priority
242 Views
I have a simple piece of code as shown below. I want to open a file and for each lin eo f the file store the value od \$code in the \$x, \$y locations of a 2D array. I want to store the value '0' in all other elements. I tried this but it dosn;t seem to work - I'm having alot of problems with uninitialised values in my array especially when I am printing!

Any help greatly appreciated,
- Troy

Input.txt:
0,0,laser
1,1,quartz
2,2,orion

#!/usr/bin/perl -w

my \$inputFile = "Input.txt";

open(INPUT, \$inputFile) || die("Could not open file!");
while(\$line=<INPUT>){
chomp \$line;
(\$x,\$y,\$code)=split(/,/, \$line);

for(\$i=0;\$i<3;\$i++){
for(\$j=0;\$j<3;\$j++){
if((\$i==\$x)&&(\$j==\$y)){
\$array1[\$i][\$j]=\$code; #if x,y match i,j store \$code in this location.
}
elsif((\$i==())&&(\$j==())){
\$array1[\$i][\$j]=0;
}
}
}
}
close INPUT;

for(\$i=0;\$i<3;\$i++){
for(\$j=0;\$j<3;\$j++){
print "\$array1[\$i][\$j]\n";
}
}
0
Question by:Troyh
1 Comment

LVL 18

Accepted Solution

kandura earned 300 total points
ID: 11839669
I think this line:

elsif((\$i==())&&(\$j==())){

doesn't do what you expect.
Why don't you always set the array elements to 0 _unless_ it already contains a value?

elsif(!defined \$array1[\$i][\$j]) {
\$array1[\$i][\$j] = 0;
}

However, it looks a bit silly to have to traverse the entire array every time. If you know there are only three elements in each dimension, why don't you initialize your array to all zeros beforehand?
0

Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment Already a member? Login.

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses
Course of the Month7 days, 15 hours left to enroll

584 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.