Reputation: 26026
The loop fails. What is wrong with the array?
I would like the regex to return B
when it parses the first string, and M
when it parses the second string.
How is such an regex constructed?
#!/usr/bin/perl
use warnings;
use strict;
my $a = "0.0 B/s";
my $b = "12.0 MiB/s";
while (defined (my $s = shift ("$a", "$b"))) {
my $unit = $1 if ($a =~ m/.*([KMGT])i?B\/s$/);
print "$unit\n";
}
Upvotes: 2
Views: 92
Reputation: 37146
shift
is meant to be used with arrays, not lists. If you want to use a while
loop, you need to pre-declare an array containing $a
and $b
(which, by the way, are a bad choice for variable names).
Having said that, a for
loop construct is the more natural choice here:
for my $s ( $var1, $var2 ) { ... }
And given that you're trying to extract the measurement unit, why not do things a slightly different way:
say for map { my ( $s ) = /$regex/; $s } $var1, $var2;
Upvotes: 2
Reputation: 46768
while
has issues. $a
inside loop, when you want to use $s
.I'd use it this way:
#!/usr/bin/perl
use warnings;
use strict;
my $a = "0.0 B/s";
my $b = "12.0 MiB/s";
foreach my $s($a, $b) {
print $1 if ($s =~ m/.*([KMGT])i?B\/s$/);
}
Upvotes: 1
Reputation: 98078
You need another substitution:
for ($a, $b) {
if (m!((?:[KMGT]i)?B)/s$!) {
my $unit = $1;
$unit =~ s/(.).*/$1/;
print "$unit\n" if $unit;
}
}
Upvotes: 1