I am a beginner Perl student. I want to find different ways to do loops and modify an array from a function. So, here is what I have written so far. The last one ChangeArray6() doesn't work, and I don't know why. Also, what's the best way to deal with arrays? If my sub needs to change an array's contents, how should I write my code? What's the neatest, best, most memory-efficient way to do it from a sub?
use strict;
use warnings;
my @A = (0) x 20;
PrintA(); ChangeArray1();
PrintA(); ChangeArray2(@A);
PrintA(); ChangeArray3(@A);
PrintA(); ChangeArray4(@A);
PrintA(); ChangeArray5(\@A);
PrintA(); ChangeArray6(@A);
PrintA();
#
# This function changes an array
#
sub ChangeArray1
{
my $i = 0;
LOOP:
return if ($i >= @A);
$A[$i++] = 1; # Write to global array
goto LOOP;
}
sub ChangeArray2
{
my $REF = \@_; # get reference
for (my $i = 0; $i < @$REF; $i++)
{
$$REF[$i] = 2;
}
}
sub ChangeArray3
{
foreach my $X (@_) # $X = reference to each item
{
$X = 3;
}
}
sub ChangeArray4
{
my $i = @_;
while ($i-- > 0)
{
$_[$i] = 4; # use direct reference
}
}
sub ChangeArray5
{
my $B = shift; # I don't understand this, but it works :P
foreach my $X (@$B)
{
$X = 5;
}
}
sub ChangeArray6
{
@_ = (6) x @_; # This does not work.
}
sub PrintA { print "\n".join('', @A); }
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|