This is the only real example I could find in my own code, essentially it is a method on a base collection class to cause the collection to appear to be sorted on an arbitrary attribute (or attributes) of the objects in the collection. It uses eval to dynamically create a sort sub from a list of comparison specifications passed as an argument. Okay it doesn't fit the the 'small' criteria but I think it is illustrative of the kind of use string eval is good for:
sub sort
{
my ( $self, $sort_spec ) = @_;
my $sort_done = 0;
if ( defined $sort_spec )
{
my @sort_objs;
foreach my $obj ( @{$self->{_data}} )
{
my $sv = [];
push @{$sv}, $obj->factory_index();
foreach my $spec ( @{$sort_spec} )
{
my $meth = $spec->{Key};
push @{$sv}, $obj->$meth();
}
push @sort_objs, $sv;
}
my @comparisons = ();
my $index = 0;
foreach my $spec ( @{$sort_spec} )
{
$index++;
my $comp = '';
my ($left_arg, $right_arg) = ('$a','$b');
if ( exists $spec->{Direction} and $spec->{Direction} eq '-' )
{
( $left_arg, $right_arg) = ('$b', '$a');
}
if ( $spec->{Compare} eq 'cmp' || $spec->{Compare} eq '<=>' )
{
$comp = "${left_arg}->[$index] $spec->{Compare} ${right_arg}
+->[$index]";
}
else
{
$comp = "$spec->{Compare}(${left_arg}->[$index],${right_arg}-
+>[$index])";
}
push @comparisons, $comp;
}
if ( $index )
{
my $sub = join ' || ' , @comparisons;
$sub = "sub { $sub };";
*sortsub = eval $sub;
$self->{_sort_index} = [];
@{$self->{_sort_index}} = map { $_->[0] }
sort sortsub @sort_objs;
$sort_done = 1;
my $index = 0;
foreach my $obj ( $self->list() )
{
$obj->factory_index($index++);
}
}
}
return $self->{_sorted} = $sort_done;
}
/J\
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|