Re: s/// w/o intermediate variables?

Marcus Holland-Moritz <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <20040504173802.3adab6b6@r2d2>
On 2004-05-04, at 11:13:38 -0400, [email protected] wrote:

> Here's an example of a recurrent annoyance:
> 
>   my $package = 'Foo::Bar::Baz';
>   (my $package_filename = $package) =~ s,::,/,g;
>   require $package_filename;
>   $package->foobar();
> 
> One of my many neurotic little peeves is that, unless code readability
> absolutely demands it, I hate defining variables that will be used
> only once, such as $package_filename above.  I would like to be able
> to do something like
> 
>   my $package = 'Foo::Bar::Baz';
>   require TRANSFORM[ s,::,/,g, "$package.pm" ];
>   $package->foobar();
> 
> where TRANSFORM[] stands for an expression in which an "s-expression"
> (i.e. one using s///) is applied to a string, and the resulting string
> is returned as the result.
> 
> Of course, I could define a helper sub to do this:
> 
>   sub transform {
>     my $s_expression = shift;
>     local $_ = shift;
>     eval $s_expression;
>     die $@ if $@;
>     $_
>   }
> 
> But is there a way to achieve this result without defining such a
> helper sub?

Something like

  mhx@r2d2 ~ $ cat /tmp/xxx.pl 
  my $package = 'Data::Dumper';
  require do { my $_="$package.pm"; s,::,/,g; $_ };
  print $package->Dump([$package]);

  mhx@r2d2 ~ $ bleadperl /tmp/xxx.pl 
  $VAR1 = 'Data::Dumper';

?

Ok, it uses $_, but only scoped, and $_ is there anyway.

(You may s/my \$_/local \$_/ for backwards compatibility.)

Marcus

> kynn
> 
> P.S. I couldn't come up with a sufficiently general transform sub such
> that its first argument is a qr-quoted regexp.  Is there a way to do
> this that approaches the level of generality of the eval kluge above?
> 


-- 
BOFH Excuse #189:

SCSI's too wide.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.