Thread Currying in Schleifen (18 answers)
Opened by flowdy at 2012-11-06 22:47

topeg
 2012-11-14 17:30
#163309 #163309
User since
2006-07-10
2611 Artikel
BenutzerIn

user image
"undef" ist auch ein Wert der zurück geben werden kann.

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
sub climb_up
{
  my $self=shift;

  # nur gerade Anzahl von Werten
  pop(@_) if(@_%2);
  my %options=@_;

  unless($options{code_find} and ref($options{code_find}) eq 'CODE')
  { croak(qq(in method "climb_up" "code_find" had to be defined! )); }

  $options{return_found}=1 unless(exists $options{return_found});

  $options{break_on_undef}=1 unless(exists $options{break_on_undef});

  my @ret;
  my $now=$self;

  while ( $now = $now->parent_row )
  {
    my @r=$options{code_find}->($now);
    last if($options{break_on_undef} and @r==1 and !defined($r_[0]));
    push(@ret,@r) if($options{return_found});
  }

  return 1 unless($options{return_found});
  return @ret;
}


Der Aufruf wäre dann:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
$obj->climb_up(code_find=>sub{
    my $obj=shift;
    if('was auch immer')
    { return qw(irgend ein array); } # kein Abbruch
    elsif('noch eine Auswahl')
    { return (); } # kein Abbruch
    elsif('noch eine Auswahl')
    { return undef,undef; } # kein Abbruch
    else
    { return undef; } # Abbruch
  });




Oder eine alternative mit zwei Funktionen.

more (13.9kb):

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
36
37
38
39
40
sub climb_up
{
  my $self=shift;

  # nur gerade Anzahl von Werten
  pop(@_) if(@_%2);
  my %options=@_;

  $options{return_found}=1 unless(exists $options{return_found});

  my $ok=2;

  if(!$options{code_find} or ref($options{code_find}) ne 'CODE')
  {
    $ok--;
    $options{code_find}=sub{};
    $options{return_found}=0;
  }

  if(!$options{code_test} or ref($options{code_test}) ne 'CODE')
  {
    $ok--;
    $options{code_test}=sub{1};
  }
  
  unless($ok)
  { croak(qq(in method "climb_up" "code_find" or "code_test" had to be defined! )); }

  my @ret;
  my $now=$self;

  while ( $now = $now->parent_row )
  {
    my @r=$options{code_find}->($now);
    last unless( $options{code_test}->($now,@r) );
    push(@ret,@r) if($options{return_found});
  }

  return @ret;
}


Der Aufruf wäre dann:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
my $run=1;
$obj->climb_up(
  code_find=>sub{
    my $obj=shift;

    $run=0 unless('was auch immer');

    return qw(irgend ein array);
  },
  code_test => sub{
    my $obj=shift;
    my @values=@_;

    return $run;
  }
);


oder:

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
my $break=0;
$obj->climb_up(
  code_test => sub{
    my $obj=shift;

    return 1 if('was auch immer');
    return 0; # abbruch
  }
);



modedit Editiert von pq: more-tag
Last edited: 2012-11-14 17:50:04 +0100 (CET)

View full thread Currying in Schleifen