karthikasasanka has asked for the wisdom of the Perl Monks concerning the following question:

While I was working with delete function. I got a doubt that, how delete function is able to identify the difference between normal scalar and array scalar.

eg.

delete $arr[0]; #it works delete $scalar; #it throws error delete $hash{$key}; #it works

I want to know whether we can write subroutines which can detect the scalar and array element and how? if any one has an idea on this, please let me know.

Replies are listed 'Best First'.
Re: argument to delete function
by moritz (Cardinal) on Jun 15, 2010 at 13:30 UTC
    As far as I know, delete and exists are special-cased by the parser, so you can't write your own function that behaves like either of them in pure Perl. (Might be possible with XS, not sure).

      Should be doable with a source filter, so technically Perl, though "pure" might be a very, very strong word to use with regard to source filters. :-)

      Note to OP: no, you don't want to write a source filter.

Re: argument to delete function
by ikegami (Patriarch) on Jun 15, 2010 at 16:26 UTC

    I want to know whether we can write subroutines which can detect the scalar and array element and how?

    No, all a sub receives is scalars.

    delete is handled specially by the parser.

    delete($a[0]);
    is compiled into something like
    delete(\@a, 0);

    What are you actually trying to do?

Re: argument to delete function
by almut (Canon) on Jun 15, 2010 at 13:38 UTC
    whether we can write subroutines which can detect the scalar and array element

    As the delete builtin can syntactically only be applied to array or hash elements, I'm not sure what (and why) you'd want to detect...  Could you elaborate on your use case?

Re: argument to delete function
by jwkrahn (Abbot) on Jun 15, 2010 at 18:53 UTC

    You are assuming that delete only works with scalars, which is not true:

    $ perl -le'my @x = "a".."z"; print "@x"; delete @x[2,4,6,8]; print "@x +"' a b c d e f g h i j k l m n o p q r s t u v w x y z a b d f h j k l m n o p q r s t u v w x y z $ perl -le'my %x = "a".."z"; print "@{[%x]}"; delete @x{qw/c g k/}; pr +int "@{[%x]}"' w x e f a b m n s t y z u v c d k l q r g h i j o p w x e f a b m n s t y z u v q r i j o p
Re: argument to delete function
by Anonymous Monk on Jun 15, 2010 at 13:39 UTC
    how delete function is able to identify the difference between normal scalar and array scalar.

    perl magick :)

    I want to know whether we can write subroutines which can detect the scalar and array element and how?

    The easy way might involve one of the B modules (if its possible), and the hard way would involve hacking perl

    if any one has an idea on this, please let me know.

    Why do you want this? Maybe you want to tie an array or a hash instead?