> -----Original Message-----
> From: Tyler Longren [mailto:[EMAIL PROTECTED]]
> Sent: Friday, August 10, 2001 10:19 AM
> To: Perl-Beginners
> Subject: number of elements in array is -1?
>
>
> Hello everyone,
>
> I have a problem. I just want to print the number of elements in an
> array. Here's the code:
> my @scans;
> my $last_host = "192.168.1.1";
> while (<LOGFILE>) {
> push (@scans, $_)
> if m/$last_host/i;
> }
>
> shouldn't that put all of the results into the @scans array? I know
> there'd just be a bunch of the same value.
> $array[0] would equal 192.168.1.1
> and $array[1] would equal 192.168.1.1
>
> I try to show the number of elements in the array like so:
> print "$#scans";
That shows the index of the last element. -1 means the array is empty.
To show the number of elements, use:
print scalar @scans;
>
> But that prints "-1". I know for a fact there are at least 2
> entries in
> LOGFILE that have an IP of 192.168.1.1.
Your program works when I feed it data containing 192.168.1.1, so
I'd say check your data again.
Note that in your regex, the .'s will match any character. To
match a literal dot, you need to escape them:
my $last_host = "192\\.168\\.1\\.1"; # not recommended
my $last_host = '192\.168\.1\.1'; # better
Note also that if $last_host does not change during the execution
of your program, you should add the /o option to the m// so the
regex is only compiled once.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]