in reply to Re^5: If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
in thread If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?

Ah, I've stumbled over this: Parameters which are only needed at object creation, but which don't need to stick around (or shouldn't, in the case of a password).

Contrary to my previous post, where I advocated to use this only to keep APIs compatible, this is another example where I find coercion to be an excellent tool. Something sort of like this (note I'm not familiar with Moo coercion which seems to be different from Moose coercion, so caution is advised):

package Moo::Role::DBIConnection; use Moo::Role; use feature 'signatures'; no warnings 'experimental::signatures'; use DBI; our $VERSION = '0.01'; =head1 NAME Moo::Role::DBIConnection =head1 SYNOPSIS { package My::Example; use Moo 2; with 'Moo::Role::DBIConnection'; }; # Connect using the parameters my $writer = My::Example->new( dbh => { dsn => '...', user => '...', password => '...', options => '...', }, ); # ... or alternatively if you have a connection already my $writer2 = My::Example->new( dbh => $dbh, ); =cut has 'dbh' => ( is => 'ro', coerce => \&_coerce_db, ); sub _coerce_db { my $connection_data = shift; return UNIVERSAL::isa($connection_data,'DBI::db') ? $connection_data : DBI->connect( @$connection_data{qw(dsn user password options)} + ); } 1;
Edited to add: 1nickt was faster and more comprehensive with the same proposal. I upvoted his, feel free to ignore mine.
  • Comment on Re^6: If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
  • Download Code

Replies are listed 'Best First'.
Re^7: If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
by 1nickt (Canon) on Oct 16, 2019 at 01:32 UTC

    "feel free to ignore mine"

    au contraire! Your solution is identical ... down to the hashref slice and the lack of parameter checking (allowing DBI to raise whatever its exception is). I upvoted your post too and I'm pleased to see it, not least because it makes me more confident my suggested approach was a good one. Keep posting!


    The way forward always starts with a minimal test.

      Thank you both for this example! I think it will help me move much of this kind of stuff away from accessors.

      Now that you have mentioned this, I seem to remember something similar being mentioned in that talk, but only as "What he really wants are coercions", but that mention wasn't made loud or raised for discussion. In any case, your posts showed me how Moo* wants to be used for building nicer constructors and how I can eliminate the bad part of my constructors without resorting to the real manual parsing of the constructor arguments again.