http://www.perlmonks.org?node_id=1040663


in reply to Test if multiple variables are defined

What about a simple grep like this?

s/^\s+|\s+$//g grep {defined $_} for ( $ipaddress, $prefix, $interface, $device, $locati;

The syntax above might not be perfect, there may be a comma or something else needed, but it conveys the idea, I think.

UPDATE:

I typed the above without having a chance to test and I stupidly misplaced my "for". I really meant to write:

s/^\s+|\s+$//g for grep {defined $_} ( $ipaddress, $prefix, $interface, $device, $location);

That probably makes much more sense (the "for" is totally useless between the grep block and the list, but, as placed now, it should give the grep results one by one aliased to $_ to the s/// statement), but that still does not work properly (for some reason, I have trouble using for and foreach with map or grep, it often does not really work the way I expect). So, having now a chance to test, I can change it somewhat to get it working the way I wanted:

my @result = map {s/^\s+|\s+$//g; $_}  grep {defined $_} ( $ipaddress, $prefix, $interface, $device, $location);

or simply

map {s/^\s+|\s+$//g; $_}  grep {defined $_} ( $ipaddress, $prefix, $interface, $device, $location);

However, using map in this context is probably not be the best, because it is not completely obvious to the eye that the elements of the original list are modified by the command.

Replies are listed 'Best First'.
Re^2: Test if multiple variables are defined
by Eily (Monsignor) on Jun 25, 2013 at 22:03 UTC

    What about a simple grep like this?

    s/^\s+|\s+$//g grep {defined $_} for ( $ipaddress, $prefix, $interface, $device, $locati;

    That wouldn't work, s/// either works on the string binded to it with =~ (or !~) or on $_ otherwise, not on a list parameter. Look at AnomalousMonk's answer for the correct syntax.

      Yes, you are right and I definitely know it. As noted in my update above, I really meant to write:

      s/^\s+|\s+$//g for grep {defined $_} ( $ipaddress, $prefix, $interface, $device, $location);

      But, as I also said in my update, that does not work as I expected, the "for" does not seem to deliver to the s/// statement the elements supplied by the grep. I got it working quite easily using a map instead of a for, but it no longer has the relative cleverness I was looking for.

        use strict; use warnings; use Data::Dumper; my ( $ipaddress, $prefix, $interface, $device, $location) = ('no_ws', +' some_ws ', undef, ' lotsa ws ', undef); s/^\s+|\s+$//g for grep {defined $_} ( $ipaddress, $prefix, $interface +, $device, $location); print Dumper ( $ipaddress, $prefix, $interface, $device, $location);
        (Thanks AnomalousMonk for the strings :D). So this yields:
        $VAR1 = 'no_ws'; $VAR2 = 'some_ws'; $VAR3 = undef; $VAR4 = 'lotsa ws'; $VAR5 = undef;
        It works fine.

        Alright, I must have done something else wrong in my test. Thank you for your message.