Bennco99 has asked for the wisdom of the Perl Monks concerning the following question:

How do I take "$objItem->{DNSHostName}" and make it a variable to use later in the script. It seems to go away after the foreach is done.
use Win32::OLE('in'); use constant wbemFlagReturnImmediately => 0x10; use constant wbemFlagForwardOnly => 0x20; $computer = "10.1.50.57"; $objWMIService = Win32::OLE->GetObject ("winmgmts:\\\\$computer\\root\\CIMV2") or die "WMI connection fai +led.\n"; $colItems = $objWMIService->ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration","WQL",wbemFlagR +eturnImmediately | wbemFlagForwardOnly); foreach my $objItem (in $colItems) { next unless $objItem->{Description} eq "Intel 8255x-based +Integrated Fast Ethernet"; print "DNS Host Name: $objItem->{DNSHostName}\n"; print "IP Address: " . join(",", (in $objItem->{IPAddress})) . " +\n"; print "MAC Address: $objItem->{MACAddress}\n"; print "\n"; }
Something like..
$pcname = "$objItem->{DNSHostName}"
Thank you

Replies are listed 'Best First'.
Re: forward variable...
by ikegami (Patriarch) on Aug 10, 2006 at 16:24 UTC

    You gave the answer already (except the quotes are not needed).

    my $pcname; foreach my $objItem (in $colItems) { next unless $objItem->{Description} eq "..."; $pcname = $objItem->{DNSHostName}; last; }

    One catch. What happens if there 0 or 2+ matching records? You could store them in an array.

    my @pcnames; foreach my $objItem (in $colItems) { next unless $objItem->{Description} eq "..."; push(@pcnames, $objItem->{DNSHostName}); }

    By the way, the first snippet can also be written as

    use List::Util qw( first ); my $pcname = map { $_->{DNSHostName} } first { $_->{Description} eq "..." } in $colItems;

    The second snippet can also be written as

    my @pcnames = map { $_->{DNSHostName} } grep { $_->{Description} eq "..." } in $colItems;

    If you're expecting one, and only one match, you could easily check the number of entries in @pcnames.

    my @pcnames = map { $_->{DNSHostName} } grep { $_->{Description} eq "..." } in $colItems; die("Unable to find network card\n"); if @pcnames == 0; warn("Found multiple network cards. Using the first one\n") if @pcnames != 1; my $pcname = $pcnames[0];
Re: forward variable...
by prasadbabu (Prior) on Aug 10, 2006 at 16:23 UTC

    Hi Bennco99,

    If i understood your question correctly, i think you are looking for symbolic references, which you have to avoid fully. Instead you can use hash or array to use it later. Take a look at perlvar.

    $hash{pcname}= "DNSHostName"

    Here are some nodes that may help you to understand better symbolic references, Re: Dynamically naming and creating hashes

    Update: Sorry, misunderstood the question. Ignore this. Ikegami thanks for pointing out :)

    Prasad