This is where my code breaks:
use strict;
use warnings;
my @word = qw ( F O O B A R );
my $letter = 'X'; # no prob with FOOBAR if $letter = ‘A’
# Two dimensional: doesn't work
my @matrix2D; push @matrix2D, [ split '', '.......' ] for 0 .. 2;
$matrix2D[0][4] = $letter;
my @temp_matrix2D = @matrix2D;
for my $i ( 0 .. $#word ) {
unless ( $temp_matrix2D[0][$i] =~ /[.$word[$i]]/ ) {
print 'Error!: ';
@temp_matrix2D = @matrix2D;
last;
}
$temp_matrix2S[0][$i] = $word[$i];
}
@matrix2D = @temp_matrix2D;
print "@{$matrix2D[0]}\n";
# prints “Error: F O O B X . .’, which I don’t want
# One dimensional: works, but no good to me...
my @matrix = split '', '.......';
$matrix[4] = $letter;
my @temp_matrix = @matrix;
for my $i ( 0 .. $#word ) {
unless ( $temp_matrix[$i] =~ /[.$word[$i]]/ ) {
print 'Error!: ';
@temp_matrix = @matrix;
last;
}
$temp_matrix[$i] = $word[$i];
}
@matrix = @temp_matrix;
print "@matrix\n";
# prints “Error!: . . . . X . .’, which is what I want
As might|mightn’t be obvious from the above, I am endeavouring to write a crossword/scrabble type programme. This extract simulates my attempt to check whether the user-entered word (simplified here to @word) fits in the existing (already partially filled) grid, given the user-entered coordinates (simplified here to
[0,0,h] where ‘h’ is horizontal). If the word fits with the letters already in the matrix, no problem, let’s change the grid to include it and move on (this works, as illustrated by changing $letter to 'A'). If the word doesn’t fit, however, I need to: (a) print a warning (easy); (b) redo (or whatever) a loop that doesn’t concern us here in order to get new user input; (c) crucially, recuperate my matrix as it was previously. That is to say, based on the above snippet, I want the first ‘line’ of @matrix2 to be ‘. . . . X .’ and not ‘F O O B X .’.
So, on to my question (at last):
- Is there an obvious workaround for this? I’ve scoured perllol, perldsc, perlreftut, and (to the best of my limited capacities) perlref; have I missed something?
- Or should I pursue my current idea of looping over the same data twice (which seems a waste...), first to check validity and second to insert the new word?
- Or should I use some other type of data structure, which would seem unfortunate, since an AoA appeared to be ideal for my purposes?
Thank you, knowledgeable Monks, for your input.
Dave