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

Hello,

How do I remove a NULL element from and array?

I print out my array and I'm getting ...

DATA: DATA:1 DATA:2 DATA:3 DATA:4 DATA:5
I've tried using chomp, but haven't had any luck

Any ideas?
Thanks

Replies are listed 'Best First'.
Re: Removal of "NULL" element in an array?
by Paladin (Vicar) on Jan 07, 2003 at 23:56 UTC
    splice() pop() and shift() are good if you know where the elements you want to remove are. If you want to remove all undefined elements you could use grep @foo = grep {defined} @foo;  # Only return elements that are defined You can replace defined with some other test if your definition of NULL is not definedness.
Re: Removal of "NULL" element in an array?
by submersible_toaster (Chaplain) on Jan 07, 2003 at 23:47 UTC

    If the null element is the last in the array then you can  pop @array
    Or as your example states, at the beginning of the array, shift @array
    However for anything trickier , like removing the null at $array[45] , you want to investigate splice


    Regarding chomp, chomp will only remove a newline char from a string (or array of strings).
    I can't believe it's not psellchecked
      However for anything trickier , like removing the null at $array[45] , you want to investigate splice
      or grep.
      @a = grep { $_ ne '' } @data;
Re: Removal of "NULL" element in an array?
by cchampion (Curate) on Jan 08, 2003 at 12:26 UTC

    By "NULL," do you mean only undefined items or also the empty ones?

    If you want to exclude only the items that are not defined, then use

    my @clean = grep { defined } @data;

    If you want to skip the empty items, then use

    my @clean = grep { $_ ne '' } @data;

    However, the above code will break on undefined items. If you want to combine both approaches, then the "right" approach is:

    #!/usr/bin/perl -w use strict; my @data= (1, 2, 3, 'a', undef, 4, '', 5, 'b'); my @clean = grep { defined && $_ ne '' } @data; print join ",", @clean; print "\n";

    output:

    1,2,3,a,4,5,b
    

    HTH

    cchampion