Keenan, Greg John (Greg)** CTR ** wrote:
> Hi,
Hello,
> What is the best way to only work with the first x number of elements in an
> array?
>
> At the moment this script prints the entire contents of @lines for each
> element in @cfgs
>
> I would like to restrict this to the number of elements listed in the hash
> %numTapes for each element in @cfgs
>
> Any suggestions for improving this script much appreciated.
>
>
> --start--
> use strict;
> use warnings;
>
> my $cfgDir = '/amanda/admin/etc/amanda';
> my @cfgs = qw(Toaster MFG-UNIX SYS-UNIX Amanda-Daily);
> my %numTapes = (
> "$cfgs[0]" => 6,
> "$cfgs[1]" => 5,
> "$cfgs[2]" => 5,
> "$cfgs[3]" => 1,
> );
Do you really need an array and a hash? If you need keep the order of @cfgs
you could use an array of arrays:
my @cfgs = (
[ Toaster => 6 ],
[ MFG-UNIX => 5 ],
[ SYS-UNIX => 5 ],
[ Amanda-Daily => 1 ],
);
If you don't really care about the order then just use a hash:
my %cfgs = (
Toaster => 6,
MFG-UNIX => 5,
SYS-UNIX => 5,
Amanda-Daily => 1,
);
> my $cfg;
> foreach $cfg (@cfgs) {
> my $fileIn="$cfgDir/$cfg/tapelist";
> open (FILEIN, "<$fileIn") or die ("Could not open $fileIn: $!");
> my @lines = reverse <FILEIN>;
> my $line;
> foreach $line (@lines) {
> print "$line\n";
> }
> }
Using an AoA:
for my $cfg ( @cfgs ) {
my $fileIn = "$cfgDir/$cfg->[0]/tapelist";
open FILEIN, '<', $fileIn or die "Could not open $fileIn: $!";
print +( reverse <FILEIN> )[ -$cfg->[1] .. -1 ];
}
Using a hash:
for my $cfg ( keys %cfgs ) {
my $fileIn = "$cfgDir/$cfg/tapelist";
open FILEIN, '<', $fileIn or die "Could not open $fileIn: $!";
print +( reverse <FILEIN> )[ -$cfg{$cfg} .. -1 ];
}
Also, if the files are large you can get better efficiency using the
File::ReadBackwards module.
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>