Hello:

On Thu, Nov 24, 2011 at 07:42:17PM +0100, Rob Coops wrote:
> I'm not sure what the meaning is of this but the thing that is happening is
> simple enough. You have @ARGV which contains [ 'A host name', 'A port
> number']. On line 20 you set $hostname = $ARGV[0] = 'A host name' and on
> line 21 you set $portnumber = $ARGV[1] = 'A port number'. So far so good,
> then on line 22 you assign $host the contents of $_[0] or $hostname, and on
> 23 you set $host = $_[1] or $portnumber;
> 
> Now I am not familiar enough with the perl innards to fully understand the
> logic behind this construction, but basically in this setup you will prefer
> the use of @_ over the information in @ARGV after all the value after the
> || will only be used in case the shift argument results in an
> undef assignment to $host or $port.

Not quite:

perldoc -f shift says:
> If ARRAY is omitted, shifts the @_ array within the lexical
> scope of subroutines and formats, and the @ARGV array outside
> of a subroutine and also within the lexical scopes established
> by the "eval STRING", "BEGIN {}", "INIT {}", "CHECK {}",
> "UNITCHECK {}" and "END {}" constructs.

The code as given to us by the OP is not inside of any subroutine
or format so shift will implicitly shift from @ARGV (not @_,
which wouldn't be very useful here since it's empty). So the code
the OP posted isn't doing anything useful there. It's effectively
just redundantly copying the values out of @ARGV.

For the OP, to see what shift does view the documentation with
'perldoc -f shift' or look it up online. Effectively though it
copies the first value from an array and removes it from the
array.

A preferred solution for copying parameters from a list or array
is to assign to a list of lvalues because it takes less code, the
importance of order is obvious, it doesn't modify the array, and
it's easier to add extra parameters:

my ($host, $port) = @ARGV;

Of course, if you needed to actually choose between multiple
arrays then you'd need something a bit more complicated, but I'd
probably write a sub for that. For example:

use List::Util;

sub get_ordered_params
{
    my @arrays = @_;
    my @results;

    my $length = max map { ${#$_} } @arrays;

    for my $i (0 .. $length)
    {
        for my $array (@arrays)
        {
            $results[$i] ||= $array->[$i];
        }
    }

    return @results;
}

my ($host, $port) = get_ordered_params(\@ARGV, \@_);

__END__

(Untested)

Regards,


-- 
Brandon McCaig <bamcc...@gmail.com> <bamcc...@castopulence.org>
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bamccaig.com/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'

Attachment: signature.asc
Description: Digital signature

Reply via email to