Scroll to navigation

Data::Find(3pm) User Contributed Perl Documentation Data::Find(3pm)

NAME

Data::Find - Find data in arbitrary data structures

VERSION

This document describes Data::Find version 0.03

SYNOPSIS

  use Data::Find qw( diter );
  my $data = {
    ar => [1, 2, 3],
    ha => {one => 1, two => 2, three => 3}
  };
  
  my $iter = diter $data, 3;
  while ( defined ( my $path = $iter->() ) ) {
    print "$path\n";
  }

DESCRIPTION

INTERFACE

Nothing is exported by default. Use, eg,

  use Data::Find qw( dwith );

to get the subroutines you need or call them with their fully qualified name:

  my $iter = Data::Find::diter $data;

"diter"

Given an arbitrary data structure and (optionally) an expression to match against elements in that structure returns an iterator which will yield the path through the data structure to each matching element:

  my $data = {
    ar => [1, 2, 3],
    ha => {one => 1, two => 2, three => 3}
  };
  
  my $iter = diter $data, 3;
  while ( defined ( my $path = $iter->() ) ) {
    print "$path\n";
  }

would print:

  {ar}[2]
  {ha}{one}

In other words it returns paths to each element that contains the scalar 3. The returned paths can be used in conjunction with "eval" to access the matching elements.

The match expression can be

  • a scalar
  • a regular expression
  • a code reference
  • "undef"

When the match expression is a code ref it will be passed each element in the data structure in turn and should return true or false.

  my $iter = diter $data, sub {
    my $v = shift;
    defined $v && !ref $v && $v % 2 == 1;
  };
  while ( defined ( my $path = $iter->() ) ) {
    print "$path\n";
  }

Note that the match code will see all of the elements in the data structure - not just the scalars.

If the match expression is "undef" it will match those elements whose value is also "undef".

Iterator

In a scalar context the returned iterator yields successive paths within the data structure. In an array context it returns the path and the associated element.

  my $iter = diter $data;
  while ( my ( $path, $obj ) = $iter->() ) {
    print "$path, $obj\n";
  }

"dfind"

Similar to "diter" but returns an array of matching paths rather than an iterator.

"dwith"

Similar to "diter" but call a supplied callback with each matching path.

  dwith $data, qr/nice/, sub {
    my ( $path, $obj ) = @_;
    print "$path, $obj\n";
  };

BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to "bug-data-find@rt.cpan.org", or through the web interface at <http://rt.cpan.org>.

AUTHOR

Andy Armstrong "<andy@hexten.net>"

LICENCE AND COPYRIGHT

Copyright (c) 2009, Andy Armstrong "<andy@hexten.net>".

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

2024-01-20 perl v5.38.2