Thread ref vs Scalar::Util::reftype (2 answers)
Opened by Kuerbis at 2013-05-13 15:34

Kuerbis
 2013-05-13 15:34
#167508 #167508
User since
2011-03-20
938 Artikel
BenutzerIn
[default_avatar]
Würde bei einer Funktion mit dem Namen "print_array_ref" besser ref oder besser reftype zum Testen des Arguments passen?

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use Scalar::Util qw(reftype);

package Package_a_ref;
sub new {
    return bless [ qw( a b c ) ], shift;
}

package ARRAY;
sub new {
    return bless { one => 1 }, shift;
}

package main;

sub print_array_ref_AAA {    # ref
    my ( $a_ref ) = @_;
    die ">no arguments" if not @_;
    die ">not defined" if not defined $a_ref;
    die ">not a reference" if not length ref $a_ref;
    die ">not an ARRAY reference" if ref( $a_ref ) ne 'ARRAY';
    say for @$a_ref;
}

sub print_array_ref_BBB {    # reftype
    my ( $a_ref ) = @_;
    die ">no arguments" if not @_;
    die ">not defined" if not defined $a_ref;
    die ">not a reference" if not defined reftype( $a_ref );
    die ">not an ARRAY reference" if reftype( $a_ref ) ne 'ARRAY';
    say for @$a_ref;
}



Mit ref würde es nicht richtig funktionieren, wenn das Paket "ARRAY" heißt. Aber ich vermute, dass könnte man vernachlässigen.

Code (perl): (dl )
1
2
3
4
5
eval {
    my $m = ARRAY->new();
    print_array_ref_AAA( $m );
};
if( $@ ) { say $@ }


Mit reftype könnte man eine blessed Array-Referenz ausgeben. Ist das als ein Feature oder als Fehler anzusehen?

Code (perl): (dl )
1
2
3
4
5
eval{
    my $n = Package_a_ref->new();
    print_array_ref_BBB( $n );
};
if ( $@ ) { say $@ }

Last edited: 2013-05-13 15:37:02 +0200 (CEST)

View full thread ref vs Scalar::Util::reftype