what "shift" does, if not "$_ = shift;" ?

D

devphylosoff

hey

the first line in one of my subroutine is
shift;

but in this case i cannot use $_ and think $_ = shift;
why ?

entire code:

my @gilligan = qw(a b c d e);
my @skipper = qw(1 2 3 4 5);
my @professor = qw(I II III IV V);
my %all = (
Gilligan => \@gilligan,
Skipper => \@skipper,
Professor => \@professor,
);

sub check_items_for_all {
# $_ = shift; # try this
shift;
for $key (keys %$_) {
check_required_items($key, $_->{$key});
}
}

sub check_required_items {
my $who = shift;
my $items = shift;

my @required = qw(1 2 3 I II III a b c d V);
my @missing = ( );

for my $item (@required) {
unless (grep $item eq $_, @$items) { # not found in list?
print "$who is missing $item.\n";
push @missing, $item;
}
}

if (@missing) {
print "Adding @missing to @$items for $who.\n";
push @$items, @missing;
}
}
 
P

Peter Makholm

devphylosoff said:
the first line in one of my subroutine is
shift;

This will just discard the first argument from @_. Not really usefull
in you functions as you don't use @_ later on.
but in this case i cannot use $_ and think $_ = shift;
why ?

If you think that 'shift' in void context is equal to '$_ = shift'
then you thinking is wrong. Why you think that I'm not able to tell,
the documentation for the shift function doesn't seem to imply this.

The documentation says that shift works on the @_ array if the
argument to shift is omitted. But it doesn't say anything about shift
doing other special things.

entire code:

If this is you entire code, then I have no idea what you expect. You
define some variables and two functions, but use neiter.

//Makholm
 
D

devphylosoff

sorry, I lose

print map {" @{$_} \n"} values %all;
check_items_for_all(\%all);
print map {" @{$_} \n"} values %all;

in my pasted code
 
M

Michele Dondi

You'd need
local $_ = shift;

Or better yet, use a private lexical variable instead of the global $_ variable.
my $href = shift;
for $key (keys %$href) {
check_required_items($key, $href->{$key});
}

No that 5.10 (Beta) is out, and if one wants to rely on $_ being the
topicalizer, then (s)he can use a lexical one too:

my $_=shift;

Of course, in the example above it is of no usefulness.


Michele
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top