SPUG: PERL technical interview

Jacinta Richardson jarich at perltraining.com.au
Sat Jan 21 23:22:09 PST 2006


Creede Lambard wrote:
> Come up with a good way to reverse a string. I get asked that about two out
> of three interviews, it seems like. Oh, and no one seems to like 
> 
>   print join ('', reverse( split (//, $string)));

What's wrong with:

	print scalar reverse $string;

?  It's much less complicated.  Or for those who get confused:

	print scalar( reverse $string );

Reverse in a list context reverses the elements of the list.  To reverse a list
of one element, you do nothing, so:

	print reverse $string;

does nothing (print supplies a list context).  Reverse in a scalar context
concatenates its arguments and then reverses by character.  The above solution
could also be written:

	print reverse $string ."\n";

but that confuses people who then transcribe that with a comma, removing the
scalar context that . supplies.  ;)  My favourite twist on this question is to ask:

	reverse a string:  eg reverse this -> siht esrever
	reverse just the word order in the string:
	                   eg reverse this -> this reverse

and then if you're feeling clever:
	reverse the words leaving them in place:
	                   eg reverse this -> esrever siht

It's a good test to see if the person has a good grasp of context.

All the best,

	Jacinta

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the spug-list mailing list