Hi all,
I'm pretty new to Perl. I'm trying to write a function which takes as input a 2D matrix of 0s and 1s(adjacency matrix) and changes a 0 value to 1 once where it finds a 0. The function is supposed to return the new matrix, without changing the old matrix which is passed as an argument to this function.
sub add_edge {
my (@graph) = @_;
my $node1 = int(rand(5));
my $node2 = int(rand(5));
print "Random node = $node1\n";
print "Random node = $node2\n";
my $i, $j;
if (($node1 ne $node2) and ($graph[$node1][$node2] eq 0)) {
$graph[$node1][$node2] = 1;
return $graph;
}
for ($i = 0; $i < $graph_size; $i++) {
for ($j = 0; $i < $graph_size; $j++) {
if (($graph[$i][$j] eq 0) and ($i ne $j)) {
$graph[$i][$j] = 1;
return @graph;
}
}
}
}
Suppose my @G is a 5x5 matrix of all 0s.
@H = add_edge(@G);
If I write the above statement, I get the desired result in @H. But, it also modifies my original array @G, which I don't want to happen.
So, what I'm seeking here is how to pass an array to a function and return as result another array which doesn't modify the original array.
Any suggestions would be highly appreciated.
Thanks.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.