in reply to Perl ignore arrow object operator in search/replace

There are no arrow operators in strings, the right hand side of the s///ubstitution operator  s{regex}{right} is a string, unless you use the /e modifier to signal that its code; so use s///e for code (one e is code, two ee is eval, three eee is eval eval --- insane )
  • Comment on Re: Perl ignore arrow object operator in search/replace (s/searchregex/replacestring/)
  • Download Code

Replies are listed 'Best First'.
Re^2: Perl ignore arrow object operator in search/replace (s/searchregex/replacestring/)
by LanX (Saint) on Feb 17, 2014 at 14:01 UTC
    > There are no arrow operators in strings,

    That's wrong! Variable interpolation does easily dereference hashes and arrays (i.e. within strings and substitutes).

    DB<114> $h={a=>42} => { a => 42 } DB<115> "$h->{a}" => 42

    Though coderefs seem to be excluded.

    DB<118> $sub=sub { "nope" } => sub { "???" } DB<119> "$sub->()" => "CODE(0xa5cc200)->()"

    But the @{[...]} ("local eval") trick always helps where a general /e would cause too much harm.

    DB<120> $_="X" => "X" DB<121> s/X/@{[ $sub->() ]}/ => 1 DB<122> $_ => "nope"

    see also: s/RegEx/substitutions/: Variable interpolation and when to use /e - modifiers

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      The arrow operator works in strings for dereferencing hash and array elements, but not for calling coderefs, and not for method calls.

      As well as the "@{[ ... ]}" trick, another option is "${\ ... }".

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
        I'm not sure where you are correcting me... Did I say anything different?

        But I normally avoid (recommending) the scalar deref trick cause it can only return scalars (sic ;) which can byte you heavily...

        Cheers Rolf

        ( addicted to the Perl Programming Language)