(Perl) How can I neaten up this code?

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi

I am writing some Perl here, but I am sure there must be a neater way of writing this (its horribly messy!!)

open (DATA, "/usr/local/rrdtool-1.2.19/bin/rrdtool fetch dashrrd.rrd LAST -s -60s |") || die ("Source data not found <br> $!
");
foreach my $line (<DATA>)
{
chomp $line;
$line=~ s/\://g;
push @dataarray, split(/ /, $line);
push @bigarray, [ @dataarray ];
shift @dataarray while @dataarray;
}
close (source);

Any ideas greatly appreciated

Thanks
 
Hi,

Here's one way I think you can tidy things up a bit:

Code:
open(DATA,"testfile.txt")||die "could not open file";

foreach (<DATA>) {
        chomp;
        s/\://g;
        push @bigarray,[ split(//)];
}
close (DATA);

The use of $line is removed and the magical $_ variable used instead (assuming you don't need to preserve the contents of this set from outside the loop).

The "push" command is shortened by inserting the array returned by split into @bigarray. This means that we don't need @dataarray at all.

At the end of this each element in @bigarray will be an array containing each line of textfile with the : removed and split into separate chars.

Hope that helps,
Jim
 
JIMA said:
Hi,

Here's one way I think you can tidy things up a bit:

Code:
open(DATA,"testfile.txt")||die "could not open file";

foreach (<DATA>) {
        chomp;
        s/\://g;
        push @bigarray,[ split(//)];
}
close (DATA);

The use of $line is removed and the magical $_ variable used instead (assuming you don't need to preserve the contents of this set from outside the loop).

The "push" command is shortened by inserting the array returned by split into @bigarray. This means that we don't need @dataarray at all.

At the end of this each element in @bigarray will be an array containing each line of textfile with the : removed and split into separate chars.

Hope that helps,
Jim
Thanks, getting rid of $line is definatley better, but I need to build a 2-D array so think I need to keep both @dataarray and @bigarray?

Cheers
 
Hi,

Each element of @bigarray is itself an array/list. These can be obtained by getting the element from bigarray and then using "@$" to use the scalar as a list. For example:

Code:
foreach $b (@bigarray) {
        @mypart = @$b;

        foreach $c (@mypart) {
                print STDOUT "$c\n";
        }
}

The above would go through @bigarray and obtain each element in turn. The element is then used as a list by assigning to @mypart, using the @$ notation. The contents of this are then printed out. Again, this could be shortened by using:

foreach $c (@$b)

in the second foreach statement.

Hope that helps,
Jim
 
Back
Top Bottom