in reply to Re: Half-serious quest for prefix anonymous refs taking
in thread Half-serious quest for prefix anonymous refs taking

I see a different problem with dopen

I personally believe you're perfectly right. But then this definitely belongs to the other thread.

my $x = dopen( '/dev/null', 'file-not-found', '/etc/passwd' ); sub dopen { my @t = map { my $fh; open $fh, '<', $_ and <$fh> or warn "Can't open `$_': $!\n"; } @_; \@t; } __END__ Can't open `/dev/null': Can't open `file-not-found': No such file or directory

That has a different problem. It reports an error just because the file happens to be empty.

What's wrong with the ternary operator?

sub dopen { my @t = map { my $fh; open $fh, '<', $_ ? <$fh> : warn "Can't open `$_': $!\n"; } @_; \@t; }

Oh, no, please, don't tell me! It would put into @t the return value of every warning issued. (Yours would, too.) So, it must be:

do { warn "Can't open `$_': $!\n"; () }

or

(warn "Can't open `$_': $!\n")[()]

Horrible, I know! (In both cases.)

How about this, then:

my $x = dopen( '/dev/null', 'file-not-found', '/etc/passwd' ); sub dopen { my $out = []; FILE: foreach my $file ( @_ ) { my $fh; if ( ! open $fh, '<', $file ) { warn "Can't read '$file': $!\n"; next FILE; } push @{$out}, <$fh>; } return $out; } __END__ Can't read 'file-not-found': No such file or directory

Looks good! It's readable, it complains at the right times, and it doesn't die when I meant it to warn.

Well, it's an "obvious" solution. Except that instead of dereferencing $out at every iteration I would maintain it as an array and take a reference to it at the end. (Incidentally, thanks to autovivification, you don't need to initialize to an empty arrayref.) I'm far from being an optimization-fanatic, but I don't like doing useless operations.

Letting this aside, any way you look at it, these solutions take far too much code to be really in accordance with Perl's motto that "easy things should be easy." Of course, it's very perlish to use modules instead, and that's a valid alternative. But one feels that this is such a basic thing that there must must be a cheap idiom for it. One more reason for wanting some more magic in local(@ARGV), in connection with an argv pragma.

You seem to be looking for a way to do "sub dopen { [ map { open my $f, '<', $_ or warn "Can't open `$_': $!\n"; <$f> } @_ ] }" without the oh-so-confusing [] hanging around at the outskirts. My point is, that's the least of your problems.

It's not my problem (in 99% of cases) and I hope not to have implied it. I still claim that it's a very minor inconvenience that can be source for thought. You seem to fail to understand that there are not only questions about how to get things done, but that some people like to think about programming language concepts and features and about those of their preferred one.

--
If you can't understand the incipit, then please check the IPB Campaign.