in reply to Array manipulation

Since you claim to be new (like me), some comments on your code:

my $i=""; my $t=""; my @data="";

Variables that have never been used have the special undef value. What happens if you use a variable that has the undef value? Nothing serious

If you use it as a number it takes on the value 0 (zero). If you use it as a string it takes on the value of an empty string. You do not have to set them to "". You use $i and $t as numeric values in your code so setting them to "" is kinda confusing.

Setting the array @data to "" does not make much sense for an array either. If you want to empty an array assign it to an empty list:

my @data = ();

But a new array starts out this way anyway.

Now lets take a look at your loops...

$lines=scalar@data/4; for ($t=1; $t<=$lines; $t++) { for ($i=1; $i<=4; $i++) { $items=shift(@data); print $items; }

($t=1; $t<=$lines; $t++) works, but it is more common to start with $t=0 and use $t<$lines as the termination.

Getting used to this will prevent you from getting into trouble when indexing through arrays which start with an index of zero. It also prevents a finger-flub of forgetting the = in the condition.


Lou

Update: Oh, one more thing that is good to get used to when you are new. Besides using use strict;, also consider...

use warnings; # flags many questionable constructs use diagnostics; # makes error messages much more understandable

Lou

Replies are listed 'Best First'.
Re^2: Array manipulation
by wfsp (Abbot) on May 19, 2005 at 08:31 UTC
    A minor point on your update.

    The OP's code starts with:

    #!/usr/bin/perl -Tw
    So warnings are on. Taint mode is also set which will also contribute to davido's "clean and healthy life".

    Note: I am of course assuming that the w wasn't added after you posting.

Re^2: Array manipulation
by loop362 (Pilgrim) on May 19, 2005 at 01:38 UTC
    Thank you for advice Lou.
    BBEdit creates a sytax error if I don't declare the variables as empty, that is why I do it that way.
    JWG
Re^2: Array manipulation
by scmason (Monk) on May 19, 2005 at 16:36 UTC
    Good points, but I would like to make an argument why it is a good practice to intiialize variables by hand.

    Readability - traceability is important. Since Perl is not a strongly typed language, it is often more difficult to understand the authors intentions on a given variable. In C/C++/Java, you know what a variable will be used for not only by its name, but also by its type.

    By initializing a variable to the empty string or 0, you let the reader know more about your intended purposes with the variable.

    "Never take yourself too seriously, because everyone knows that fat birds dont fly" -FLC