in reply to Is "ref $date eq 'ARRAY'" wrong?

Update: Changed the foreach push to a simple push. I will now lay down the crack pipe and step away from the keyboard.

Using ref is quite frequently an indication of a design flaw. The higher level the code you're writing, the less likely it is that you'll want to use it. Here's an example that could cause a problem:

my $foo = some_func(); if ('ARRAY' eq ref $foo) { push @data => @$foo; } else { push @data => $foo; }

That's bug prone. Instead, it might be cleaner if some_func() always returned an array ref. If that's the case, the above code becomes:

my $foo = some_func(); push @data => @$foo;

The code becomes easier to read and understand as a result.

If we're talking about what a function might accept, though, I'm a bit less stringent, but it's still easy to write bugs.

sub some_func { my $self = shift; my @data = 'ARRAY' eq ref $_[0] ? @$_[0] : @_; # do stuff }

On the surface, it looks like some_funct() can take an array, a list, or an array reference, and still behaves the same, regardless. However, what happens if some tries to pass in a list where the first element is also an array ref? Program fall down and go boom.

In short, I don't disagree with using ref. Further, it might be appropriate for your program but I can't really say as I don't know what you are doing. However, any time you see someone using ref, you should look very carefully at their program to see if bugs are crawling around in there.

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Re: Is "ref $date eq 'ARRAY'" wrong?
by diotalevi (Canon) on Dec 19, 2003 at 20:49 UTC
    You couldn't possibly mean push @ary => $_! I mean, I understand using the fat arrow in some cases but you've got it pointing the wrong way. Since the arrow goes the wrong way, why aren't you using a plain comma?

      I can't make a serious justification, other than to visually group parts of an expression.

      push @array => $foo, $bar, $baz; join '|' => $foo, $bar, $baz; map func($_) => $foo, $bar, $baz;

      In this case, while the arrow appears reversed, I do it for stylistic consistency with the other expressions.

      Cheers,
      Ovid

      New address of my CGI Course.

        Hm, ok. That's an interesting idea anyway.
      You couldn't possibly mean push @ary => $_!

      No, he actually meant push @ary, @$foo; rather than looping at all ;-)

        Yes, you're absolutely correct. I got wrapped up inthe details of the problem and didn't focus on the actual code. Whoops :)

        On another note, I swear I answered this a couple of days ago, but I see in glancing at the post that I apparently didn't. Grr ...

        Cheers,
        Ovid

        New address of my CGI Course.