Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision 26353951

Von Moritz Bunkus vor fast 14 Jahren hinzugefügt

  • ID 26353951881b5334436ab599ae3979f6df5d5258
  • Vorgänger 6fda7b5d
  • Nachfolger b6aa691e

Hilfsfunktion 'ary_to_hash' für einfache Umwandlung eines Arrays in ein Hash

Unterschiede anzeigen:

SL/MoreCommon.pm
4 4
our @ISA = qw(Exporter);
5 5

  
6 6
our @EXPORT    = qw(save_form restore_form compare_numbers any cross);
7
our @EXPORT_OK = qw(ary_union ary_intersect ary_diff listify);
7
our @EXPORT_OK = qw(ary_union ary_intersect ary_diff listify ary_to_hash);
8 8

  
9
use List::MoreUtils qw(zip);
9 10
use YAML;
10 11

  
11 12
use SL::AM;
......
148 149
  return wantarray ? @ary : scalar @ary;
149 150
}
150 151

  
152
sub ary_to_hash {
153
  my $idx_key   = shift;
154
  my $value_key = shift;
155

  
156
  return map { ($_, 1) } @_ if !defined($idx_key);
157

  
158
  my @indexes = map { ref $_ eq 'HASH' ? $_->{ $idx_key } : $_->$idx_key(); } @_;
159
  my @values  = map {
160
      !defined($value_key) ? $_
161
    : ref $_ eq 'HASH'     ? $_->{ $value_key }
162
    :                        $_->$value_key()
163
  } @_;
164

  
165
  return zip(@indexes, @values);
166
}
167

  
151 168
1;
152 169

  
153 170
__END__
......
192 209

  
193 210
=back
194 211

  
212
=item ary_to_hash INDEX_KEY, VALUE_KEY, ARRAY
213

  
214
Returns a hash with the content of ARRAY based on the values of
215
INDEX_KEY and VALUE_KEY.
216

  
217
If INDEX_KEY is undefined then the elements of ARRAY are the keys and
218
'1' is the value for each of them.
219

  
220
If INDEX_KEY is defined then each element of ARRAY is checked whether
221
or not it is a hash. If it is then its element at the position
222
INDEX_KEY will be the resulting hash element's key. Otherwise the
223
element is assumed to be a blessed reference, and its INDEX_KEY
224
function will be called.
225

  
226
The values of the resulting hash follow a similar pattern. If
227
VALUE_KEY is undefined then the current element itself is the new hash
228
element's value. If the current element is a hash then its element at
229
the position VALUE_KEY will be the resulting hash element's
230
key. Otherwise the element is assumed to be a blessed reference, and
231
its VALUE_KEY function will be called.
232

  
233
=back
234

  
195 235
=cut

Auch abrufbar als: Unified diff