开发者

How can I allow an if statment to access a capture group from an above regex?

I have an if statement inside a while loop to filter out filenames that are *.iso and not *.vmdk. It works...sorta, there is just one little issue I can't figure out. When I run the code and there is a match to the if statement in the loop it makes the hash entry just like it should but because it d开发者_如何转开发oes not know the channel number of the IDE interface it just calls the hash entry "IDE" rather than "IDE0" or "IDE1".

Here is my code,

        foreach my $vm (@virtual_machines) {
        my $vmx_file = $ssh1->capture("cat $virtual_machines{$vm}{VMX}");
        my $disk_count = -1;
        my $port;
        while ($vmx_file =~ m/^(ide(?<PORT>[0-1])\:[0-1])\.fileName\s+=\s+"(?<DISK>[^"]+)["]/xmg) {
$port = "$+{port}";
            if ("$+{DISK}" =~ m/\/vmfs\/volumes\/.+?\/(?<ISO>.+?\.iso)/xm) {
                ++$disk_count;
                $virtual_disks{$vm}{"IDE$+{PORT}"}{"Disk$disk_count"} = "$+{ISO}";
            } else {
                ++$disk_count;
                $virtual_disks{$vm}{"IDE$+{PORT}"}{"Disk$disk_count"} = "$+{DISK}";
            }
        }
    }

Like I said above, the code works except for that one part. Is the way I am approaching this wrong? Do I need to make something like a loop that looks for 2 matches or something?


You are clobbering the $+ variable when you do your second regex match (the one in the if). You should save off $+{PORT} before the if.

EDIT: this demo describes what is happening in your code:

#!/usr/bin/perl

use strict;
use warnings;

my $string = "hi 1234 bye";
$string =~ /(?<num>\d+)/;
print $+{num}, "\n";
$string =~ /./;
print $+{num} || "Clobbered", "\n";

prints:

1234
Clobbered
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜