Posted on 2007-03-19 21:45:09-07 by dsch04
Dynamically creating fields

Ok, so following on from my previous posts...

Rather than explicitly adding a new field for every tag, I wondered if it would be possible to create the fields dynamically based on a list of fields in an array or hash?

So, I tried this:

my %known_tags = ( album => 1, albumartist => 1, artist => 1, }; sub create_fields { my $self = $_[0]; my $class = ref($self) || $self; foreach my $field ( keys %::known_fields ) { $class->create_field('@'.$field, ":Acc($field)"); } } sub init :Init { my ( $self, $args ) = @_; $self->create_fields; ... }

However, this doesn't seem to work. Is this approach likely to work? What am I doing wrong?

Thanks,

R.

Direct Responses: 4623 | Write a response
Posted on 2007-03-20 12:50:36-07 by jdhedden in response to 4610
Re: Dynamically creating fields
You have the basic elements, but you made it too complicated. Further, creating the fields in :Init is very bad because the it tries to recreate the field arrays each time you create an object! Here's all you need:
package Foo; { use Object::InsideOut ...; # List of tags my @known_tags = qw(album albumartist artist); # Create fields for tags __PACKAGE__->create_field('@'.$_, ":Acc($_)") foreach @known_tags; ... }
Direct Responses: 4624 | Write a response
Posted on 2007-03-20 13:01:49-07 by dsch04 in response to 4623
Re: Dynamically creating fields

Ah, thanks. That makes sense!

It's working great now.

Thanks again.

R.

Direct Responses: Write a response
Perl Weekly newsletter
A free weekly newsletter for people who are busy to read all the blogs. click here to check it out.