0

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!

Zaid
  • 36,680
  • 16
  • 86
  • 155
brike
  • 313
  • 4
  • 10

4 Answers4

3
my $count = () = $str =~ /\d+_\d+/g;
Zaid
  • 36,680
  • 16
  • 86
  • 155
  • +1, nice, I hardly understand why that works. Thought that the assignment to an empty list would reset/lose the count of elements in the original list. – Qtax Nov 27 '11 at 22:02
  • @Qtax : This is the [countof operator](http://github.com/cowens/perlopref); useful when you want to count how many items you have in your list but don't want to store it in an array. – Zaid Nov 28 '11 at 11:10
  • @Zaid Your link in the comment is dead. – FailedDev Nov 29 '11 at 14:40
  • @FailedDev : Looks like Chas needs to be notified – Zaid Nov 29 '11 at 14:44
  • 1
    @FailedDev : [Chas.](http://stackoverflow.com/users/78259/chas-owens) started the `perlopref` documentation project I tried to link to and he asked [a very interesting question](http://stackoverflow.com/questions/2897853/what-pseudo-operators-exist-in-perl-5) on SO a while ago :) – Zaid Nov 29 '11 at 19:53
  • @Zaid Oo :) Interestning indeed :) +1 for the lulz :) – FailedDev Nov 29 '11 at 19:54
1

Try:

$disk_count = scalar( split ' ', $str) - 1;
Martin York
  • 257,169
  • 86
  • 333
  • 562
Nick
  • 2,418
  • 16
  • 20
1
my @result = $str=~ m/\d_\d/g;
print "Number of disks found : ", scalar(@result), "\n"; 
FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • this answer looks the most straight forward to understand, save the output to the array, then get array account. – brike Nov 28 '11 at 02:47
  • @brike : This solution is more or less the same as mine, except that I throw the array away. – Zaid Nov 29 '11 at 14:37
0
my $counter = 0;
$counter++ while ($str =~ m/\d+_\d+/g);
snoofkin
  • 8,725
  • 14
  • 49
  • 86