Some parts of this page were machine translated.
Powered by Yandex.Translate
http://translate.yandex.com/
En el lenguaje de programación Perl tiene integrada la función de defined()
.
defined()
en Perl
En el lenguaje de programación Perl tiene integrada la función de defined()
.
A menudo esta función se utiliza para distinguir
el valor de la undef
de cualquier otro valor. Pero aún con la ayuda de
defined()
se puede saber ¿está definida la función.
undef
Principal a través de la función de defined()
es la comprobación de valores en undef
.
Si para pasar a la función defined()
valor undef
, la función devuelve falso.
La función devolverá la verdad en el caso de que el valor que le es entregada la
es cualquier cosa, pero no undef
. He aquí un ejemplo de código:
#!/usr/bin/perl
use Data::Dumper;
print Dumper defined(8);
print Dumper defined(0);
print Dumper defined('');
print Dumper defined(undef);
El resultado del trabajo de este código:
$VAR1 = 1;
$VAR1 = 1;
$VAR1 = 1;
$VAR1 = '';
A menudo la función de defined()
se utiliza para distinguir undef
de otro valor.
Pero, además, con la ayuda de defined()
se puede saber ¿está definida la función. He aquí un ejemplo de código:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
print Dumper defined(&check);
print Dumper defined(&Data::Dumper::Dumper);
La función de check()
no está definida, por lo que defined()
devolverá falso, Y he aquí la función de Dumper
hay en el paquete de Data::Dumper
y defined()
devolverá la verdad.
Eso es lo que sacará de este programa en la pantalla:
$VAR1 = '';
$VAR1 = 1;
En caso de que la función de defined()
no se transfieren a ningún argumento, la función trabaja con la variable $_
:
Si para pasar a la función defined()
más de un argumento, lo que se producirá un error y la aplicación de programas
se detiene:
Too many arguments for defined operator at script.pl line 3, near "3)"
Execution of script.pl aborted due to compilation errors.
El resultado de la operación de la función de defined()
— siempre es un valor booleano. La verdad o la mentira.
Hace mucho tiempo la función de defined()
ha trabajado de manera especial si a transferir a
la matriz o el hash como argumento. Pero ya en Perl 5.8 tal uso
daba una advertencia, y a partir de 5.22 tal uso se ha vuelto a recibir un error.
He aquí un ejemplo de código en el que en defined()
se pasa una matriz:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @arr;
print Dumper defined(@arr);
El resultado del trabajo de este código en perl versión 5.8:
defined(@array) is deprecated at script.pl line 10.
(Maybe you should just omit the defined()?)
$VAR1 = '';
Y el resultado del trabajo de la misma cuando en perl 5.30:
Can't use 'defined(@array)' (Maybe you should just omit the defined()?) at script.pl line 10.
Y el mismo código, pero sobre los hash:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %h;
print Dumper defined(%h);
Los resultados del trabajo en perl 5.8 y 5.30:
defined(%hash) is deprecated at script.pl line 10.
(Maybe you should just omit the defined()?)
$VAR1 = '';
Can't use 'defined(%hash)' (Maybe you should just omit the defined()?) at script.pl line 10.
He aquí el resultado del comando perldoc -f defined
:
defined EXPR
defined Returns a Boolean value telling whether EXPR has a value other
than the undefined value "undef". If EXPR is not present, $_
is checked.
Many operations return "undef" to indicate failure, end of
file, system error, uninitialized variable, and other
exceptional conditions. This function allows you to
distinguish "undef" from other values. (A simple Boolean test
will not distinguish among "undef", zero, the empty string, and
"0", which are all equally false.) Note that since "undef" is
a valid scalar, its presence doesn't necessarily indicate an
exceptional condition: "pop" returns "undef" when its argument
is an empty array, or when the element to return happens to be
"undef".
You may also use "defined(&func)" to check whether subroutine
&func has ever been defined. The return value is unaffected by
any forward declarations of &func. A subroutine that is not
defined may still be callable: its package may have an
"AUTOLOAD" method that makes it spring into existence the first
time that it is called; see perlsub.
Use of "defined" on aggregates (hashes and arrays) is
deprecated. It used to report whether memory for that
aggregate had ever been allocated. This behavior may disappear
in future versions of Perl. You should instead use a simple
test for size:
if (@an_array) { print "has array elements\n" }
if (%a_hash) { print "has hash members\n" }
When used on a hash element, it tells you whether the value is
defined, not whether the key exists in the hash. Use "exists"
for the latter purpose.
Examples:
print if defined $switch{D};
print "$val\n" while defined($val = pop(@ary));
die "Can't readlink $sym: $!"
unless defined($value = readlink $sym);
sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
$debugging = 0 unless defined $debugging;
Note: Many folks tend to overuse "defined" and are then
surprised to discover that the number 0 and "" (the zero-length
string) are, in fact, defined values. For example, if you say
"ab" =~ /a(.*)b/;
The pattern match succeeds and $1 is defined, although it
matched "nothing". It didn't really fail to match anything.
Rather, it matched something that happened to be zero
characters long. This is all very above-board and honest.
When a function returns an undefined value, it's an admission
that it couldn't give you an honest answer. So you should use
"defined" only when questioning the integrity of what you're
trying to do. At other times, a simple comparison to 0 or ""
is what you want.
See also "undef", "exists", "ref".