Jeff Westman wrote: > > Rob Dixon <[EMAIL PROTECTED]> wrote: > > > Jeff Westman wrote: > > > > > > If I have an array and want to take the first element off and return it, > > I > > > would do it like this: > > > > > > return (@myArray) ? shift(@myArray) : undef; > > > > > > How would I do similarly with a hash? I have something like this: > > > > > > > > > return (exists $myHash{$val1} ) ? $Hash{$val2} : undef; > > > > > > But these leaves the value in the hash. I know I can save the value > > first, > > > then DELETE it, and then return it. But I'd like to do it all in one > > step. > > > > Hi Jeff. > > > > The 'shift' built-in returns 'undef' if its operand is an empty array. > > > > Likewise, 'delete' returns either the element deleted or 'undef' if > > it didn't exist. > > I didn't know 'delete' returned the value as well. Simple and perfect!
Having posted that I wondered whether you really meant what you wrote, i.e. that you want to return and delete $Hash{$val2} based on whether or not $myHash{$val1} exists. If that's correct then you still need the conditional expression, but it seemed a little unlikely? > > It's also usual to omit 'return' on the last line of a subroutine, > > so you could just write: > > > > shift @myArray; > > > > and > > > > delete $myHash{$val1} > > > > to do what you want. > > I know perl returns the last value (statement?) by default, The returned value is the value of the last executed statement as long as that statement was an expression. If not then I'm unclear as to the exact behaviour. sub test { my $v = 0; for (1 .. 10) { $v++; } } returns the empty string (false, but not 'undef') Maybe somebody else knows? > but doesn't it make it more readable (or self-documenting) to > the next person who may come along what my intent is? IMO it would make it more obvious and wouldn't do any harm, but I've seen very little code written like that. It depends on whether you want your code to be 'familiar' or 'explicit'. Take a look at perldoc perlstyle for similar stuff. Cheers, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]