On Jan 29, Mallik said:

>Can anybody explain the functionality of eval in brief?

For starters, please read 'perldoc -f eval'.  All Perl functions are
explained in detail in the standard documentation.

eval() has two forms.  The first takes a string, and treats it as Perl
code.  It compiles and executes it, returning whatever value is
appropriate.  If there is a fatal error, it sets the $@ variable.

  my $string = "make the vowels capitals";
  my $from = "aeiou";
  my $to = "AEIOU";

  eval "\$string =~ tr/$from/$to/";
  # now $string is mAkE thE vOwEls cApItAls

We had to use eval() here, because tr/// doesn't interpolate variables.
If we'd just done

  $string =~ tr/$from/$to/;

we'd be changing $ to $, f to t, r to o, o to o, and m to o, and the
string would be "oake the vowels capitals".

The other form is eval { CODE }.  This executes a block of code in a
fail-safe environment.  If there are any fatal errors, the $@ is set, and
the block is exited.  A common use for this is:

  print "Give me a number: ";
  chomp(my $n = <STDIN>);
  my $result = eval { 100 / $n };
  if ($@) { print "You tried dividing by zero.\n" }

Basically, if we didn't use eval { } here, the program would die if the
user entered the number 0.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to