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

Georg Moritz <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <[email protected]>
From the keyboard of [email protected] [04.05.04,11:13]:

>
>
>
>
> 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?

what you require is a modifier for the s/// operator (perhaps 'r') which
makes s/// return the transformed string as a result rather than the
number of occurences of the pattern, assigning the value of a variable to
a local $_ (for the s/// operator to work with) and storing the result in
a kin of the builtins $_,$',$` and $& - let's assume $§:

$package = s,::,/,gr; # assign $package to $_, do the s/// and store result
require $§;

AFAIK there's no such thingy. All you can do is storing the resulting
strings elsewhere (in a local $_ for instance) or have it being returned
by some helper function.

I might be wrong :-)

> 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?

I guess, no, because you can't pass the modifiers to s/// as a variable
like so

s/$pat/$repl/$mod

Again, I might be wrong...

greets,
georg

-- 
_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s,/,($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e,e && print}
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.