当移动到单独的函数时,Perl行不起作用

时间:2016-06-13 10:53:00

标签: perl

我有一个可能或可能不像[0, 1]的数组,我想测试它。

此代码(在方法内)有效:

sub some_other_method {
    my $self = shift;
    ...
    if (scalar @myArray == 2 && @myArray[0] == 0 && @myArray[1] == 1) {
        # this will successfully catch arrays that look like [0, 1]
    }
}

如果我将if的内容移动到单独的方法然后调用它,它就不起作用。

sub is_warning {
    my $self = shift;
    my @array = shift;
    return scalar @array == 2 && @array[0] == 0 && @array[1] == 1;
}

...

sub some_other_method {
    my $self = shift;
    ...
    if ($self->is_warning(@myArray)) {
        # this will not catch arrays that look like [0, 1]
    }
}

如果我向print @array;添加is_warning,则只打印一个数字。

我做错了什么?

2 个答案:

答案 0 :(得分:5)

你错过了一些关于Perl的重要事情 - 一个子程序只是永远传递了@_中的标量值列表。因此,要传递数组,您需要使用下面的子例程stuffother中的一种技术。

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;

sub stuff {
   my ( $arg, @other_args ) = @_;
   print Dumper \@other_args;
   print "$_\n" for @other_args;
}

sub other {
   my ( $arg, $array_ref ) = @_;
   print Dumper $array_ref;
   print "$_\n" for @$array_ref;
}

my $param = "fish";
my @array = ( "wiggle", "wobble", "boo" );

stuff( $param, @array );
other( $param, \@array );

stuff中,子程序会传递一个值列表来处理它的内容。在other中,它为$param提供了两个值 - @array引用

在您的情况下,1仅提取shift的原因是,@_仅提取print Dumper \@_; 一个值。所以任何额外的争论都会落后。你可以看到这个;

    class UserManager(BaseUserManager):

  def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
    now = timezone.now()
    if not username:
      raise ValueError(_('The given username must be set'))
    email = self.normalize_email(email)
    user = self.model(username=username, email=email,
             is_staff=is_staff, is_active=True,
             is_superuser=is_superuser, last_login=now,
             date_joined=now, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

  def create_user(self, username, email=None, password=None, **extra_fields):
    return self._create_user(username, email, password, False, False,
                 **extra_fields)

  def create_superuser(self, username, email, password, **extra_fields):
    user=self._create_user(username, email, password, True, True,
                 **extra_fields)
    user.is_active=True
    user.save(using=self._db)
    return user


class User(AbstractBaseUser, PermissionsMixin):
  username = models.CharField(_('username'), max_length=30, unique=True,
    help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'),
    validators=[
      validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), _('invalid'))
    ])
  first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
  last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
  email = models.EmailField(_('email address'), max_length=255, unique=True)
  is_staff = models.BooleanField(_('staff status'), default=False,
    help_text=_('Designates whether the user can log into this admin site.'))
  is_active = models.BooleanField(_('active'), default=True,
    help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
  date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
  receive_newsletter = models.BooleanField(_('receive newsletter'), default=False)
  birth_date = models.DateField(_('birth date'), auto_now=False, null=True)
  address = models.CharField(_('address'), max_length=30, blank=True, null=True)
  phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
  phone_number = models.CharField(_('phone number'), validators=[phone_regex], max_length=30, blank=True, null=True) # validators should be a list

  USER_TYPES = (
    ('Farmer', 'Farmer'),
    ('Windmill owner', 'Windmill owner'),
    ('Solar panel owner', 'Solar panel owner'),)
  user_type = models.CharField(_('user type'), choices=USER_TYPES, max_length=30, blank=True, null=True)

  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['username',]

  objects = UserManager()

  class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

  def get_full_name(self):
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

  def get_short_name(self):
    return self.first_name

  def email_user(self, subject, message, from_email=None):
    send_mail(subject, message, from_email, [self.email])

答案 1 :(得分:-6)

请删除my $ self = shift;来自is_warning函数的行并再次测试它。

请尝试以下脚本:

#!的/ usr / bin中/ perl的

使用Data :: Dumper;

sub is_warning {

my @array = @_;
print Dumper \@_;
return scalar @array == 2 && @array[0] == 0 && @array[1] == 1;

}

sub some_other_method {

my @myArray = (0,1);
if (is_warning(@myArray)) {
 print "\nif inside some : @myArray\n";
}

}

some_other_method();