brike
brike

Reputation: 313

Using Perl to extract the number of matches in a string

How can I find out the number of disks in this string?

$str='disk 0_1 0_2 0_3';

In this $str, the number of disks is 3.

How can Perl output how many disks there are in this string?

Thank you!

Upvotes: 0

Views: 132

Answers (4)

Zaid
Zaid

Reputation: 37156

my $count = () = $str =~ /\d+_\d+/g;

Upvotes: 3

Nick
Nick

Reputation: 2478

Try:

$disk_count = scalar( split ' ', $str) - 1;

Upvotes: 1

FailedDev
FailedDev

Reputation: 26940

my @result = $str=~ m/\d_\d/g;
print "Number of disks found : ", scalar(@result), "\n"; 

Upvotes: 1

snoofkin
snoofkin

Reputation: 8895

my $counter = 0;
$counter++ while ($str =~ m/\d+_\d+/g);

Upvotes: 0

Related Questions