Hi All,
I was practicing with recursion in Perl and wrote a sub to reverse arrays of arrays of arrays... of arrays.
After a little trial and error I got it working:
#!/usr/local/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @array1 = (['A', 'B'], 1, 2, 3, ['One', 'Two', 'Three', ['I', 'II',
+ 'III'], 'Four'], 4);
print Dumper (\@array1);
recReverse (\@array1);
print "\n===============Reversed================\n";
print Dumper (\@array1);
my $count = 0;
sub recReverse
{
my $ref2array = shift;
if (ref $ref2array eq 'ARRAY')
{
my @newarray = reverse (@$ref2array);
@$ref2array = @newarray;
for my $item (@{$ref2array})
{
recReverse($item);
}
}
}
One thing I realized that there is the difference between
my @newarray = reverse (@$ref2array);
@$ref2array = @newarray;
and
my @newarray = reverse (@$ref2array);
$ref2array = \@newarray;
I was under the impression that both do the same thing, however I only realized that they don't.
Can someone explain the difference. I mean I have seen it in action but not sure I fully understand the concept.
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.