[Israel.pm] count chars
Yossi Itzkovich
Yossi.Itzkovich at ecitele.com
Mon Sep 3 14:09:18 EEST 2007
Hi,
I don't have a better solution, but I don't think it saves anything in
run time: not speed nor memory (assuming @matches goes out of scope very
soon).
To be able to return the scalar of a list, the list still needs to be
built.
Yossi
-----Original Message-----
From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On
Behalf Of Tal Kelrich
Sent: Monday, September 03, 2007 1:49 PM
To: perl at perl.org.il
Subject: Re: [Israel.pm] count chars
On Mon, 3 Sep 2007 13:38:05 +0300
"Amir E. Aharoni" <amir.aharoni at gmail.com> wrote:
> What is the best way to count the number of times that a character
> appears in a string?
>
> Currently i do this:
>
> ----
> my $string = "abracadabra";
> my @matches = ($string =~ /a/g);
> print scalar @matches; # 5
> print "@matches"; # a a a a a
> ----
>
> Is there a way to do it without the intermediate array?
>
> This doesn't work:
>
> ----
> my $string = "abracadabra";
> print scalar ($string =~ /a/g); # prints 1!
> ----
>
> I can use this:
>
> ----
> my $matches = ($string =~ s/(a)/$1/g);
> ----
>
> It replaces the characters with itself and returns the number of
> substitutions, but it doesn't improve readability.
>
> Any other ideas?
>
Here's another, is ugly tho
my $string = "abracadabra";
print scalar(@{[$string=~/a/g]});
--
Tal Kelrich
PGP fingerprint: 3EDF FCC5 60BB 4729 AB2F CAE6 FEC1 9AAC 12B9 AA69
Key Available at: http://www.hasturkun.com/pub.txt
----
Agree with them now, it will save so much time.
----
More information about the Perl
mailing list