in reply to DWIM Part Nineteen: Unary Operators in Void Context

UPDATE 2: As CheeseLord points out below I was on the right track ... so maybe don't ignore this post completely :) - anyway ++CheeseLord for the interesting idea

UPDATE: and the problem with me is that I post without testing and thinking properly. Ignore this post, lc is called in void context!! Thanks for making me think straight again dragonchild, I'm the one who's stupid ;-)

The problem with your suggestion is that it's not always so easy to see what's in void context and what's not. Consider for example this code with your version of lc:

sub lc_and_chomp { chomp $_[0]; lc $_[0]; # is it in void context??? } my $var = "fOobAR\n"; lc_and_chomp($var); # this alters $var print $var;
The big problem is that the lc call is now not in void context - although it may look like it at first glance ...

-- Hofmator

Replies are listed 'Best First'.
Re^2: DWIM Part Nineteen: Unary Operators in Void Context
by CheeseLord (Deacon) on Aug 21, 2001 at 18:43 UTC

    CheeseLord decides to risk exposing a possible misunderstanding of context issues...

    Actually, you're on the right track. The final line of the function is in void context because the function itself was called in void context. Tweaking your example a bit will show this:

    #!/usr/bin/perl -w use strict; use Void qw( lc ); # My lc sub lc_and_chop(\$) { chop ${$_[0]}; lc ${$_[0]}; } my $foo = 'fUnKy'; lc_and_chop $foo; print "$foo\n";

    Will print "funk". However, if we change the context of the function call...

    - lc_and_chop $foo; + my $bar = lc_and_chop $foo;

    We get "fUnK" printed out. $bar, incidentally, now contains 'funk'. So, you are correct, AFAICT. The solution would be to either switch the calls to lc and chop, or add an extra line returning what we want at the end. I was always in favor of explicit returns, anyway... (Of course, you could always not use my lc, but where would the fun be in that? ;-))

    For those interested (and for those looking for holes in my reasoning), here's what the Void::lc looks like:

    sub lc (\$) { my $ref = shift; my $val = CORE::lc $$ref; return $val if defined wantarray; $$ref = $val; }

    Update: Minor tweak to lc code. (Should do straight copy and paste next time...)

    His Royal Cheeziness

Re: Re: DWIM Part Nineteen: Unary Operators in Void Context
by dragonchild (Archbishop) on Aug 21, 2001 at 16:37 UTC
    Ok. I'm stupid. Why isn't the last line of a function in void context?

    ------
    /me wants to be the brightest bulb in the chandelier!

    Vote paco for President!

      /me shouldn't post before caffeine. Please ignore this.

      /\/\averick
      perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"