in reply to Create a new operator, get LHS

just for fun, only for strings and not really meant for serious use =)

use warnings; use strict; # true x in 'v'..'z'; # false xx in 'v'..'z'; # but variables aren't barewords my $x='x'; in->$x('v'..'z'); package in; use Data::Dump qw/pp/; our $AUTOLOAD; sub AUTOLOAD { (my $LHS= $AUTOLOAD) =~ s/in:://; #print pp [$LHS, @_]; my $res = grep {$LHS eq $_ } @_; my $not =""; $not =' not' unless $res; warn "$LHS$not @_"; return $res; }

out

/usr/bin/perl -w /tmp/in.pl x in v w x y z at /tmp/in.pl line 35. xx not in v w x y z at /tmp/in.pl line 35. x in v w x y z at /tmp/in.pl line 35. Compilation finished at Wed Aug 26 13:51:16

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^2: Create a new operator, get LHS (indirect method)
by Eily (Monsignor) on Aug 26, 2015 at 14:40 UTC

    Nice :). Your post inspired me to try something with Lvalue subroutines, I think this works quite well:

    use v5.20; use Operator qw{in}; use Variables qw{X Y Z}; my @list = 1..10; (X, Y) = (1, 11); say X." in @list" if X in @list; say Y." not in @list" unless Y in \@list; Z = 'A'; say Z." in list" if Z in ['A'..'C'];
    package Variables; use v5.20; our %V; sub import { shift; my $package = caller; no strict "refs"; for my $var (@_) { *{"$package::$var"} = sub:lvalue { @_ ? $_[0]->($V{$var}) : $V{$va +r} }; } } 1;
    package Operator; use v5.20; use List::Util qw{any none}; use Exporter 'import'; our @EXPORT_OK = 'in'; sub in(+) { my $list = shift; return sub { any { $_ eq $_[0] } @$list }; } 1;
    1 in 1 2 3 4 5 6 7 8 9 10 12 not in 1 2 3 4 5 6 7 8 9 10 A in list

    Edit: fixed the broken link for lvalue subroutines thanks to shmem.

    Edit: $V{$var} is what I meant, not $V::{$var}

      I like the idea of realizing variables as lvalue functions which evaluate passed code refs!

      Thumbs up. :)

      Not for normal Perl code, but maybe within internal DSLs which are limited to certain code areas like blocks.

      Not sure why you use a hash where a closure var could do...

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

        Not sure either. I mostly coded this without thinking it through, with several iterations of corrections. So the hash is just something I had at one point and didn't think to replace. Since I like working with closures I'd definitely use a closed-over lexical if I ever needed to use that in actual code.

        The fact that you can code something that looks like another language entirely but still is valid perl says a lot about the flexibility of the language :).

        Edit: but it wouldn't work for everything though. If X in @list; works fine, (X + Y) in @list; would fail as (X + Y) is not a subroutine call.