http://qs321.pair.com?node_id=549200


in reply to Small examples of string eval

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\