"Li Ngok Lam" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> $x = sub { $y = shift; print $y };

$x is stores a code reference.

> $X = $x;

now $X and $x both contain references to the same block of code.

> $X -> ("123"); # prints 123;

This dereferences the reference stored in $X and calls the subroutine stored
there.

> Question :
> 1. When will you use this kind of style in your code ?

This feature is used frequently. On example I have used it for is debugging:

[EMAIL PROTECTED] trwww]$ perl
@subs = (
  sub { print('Entering: ', ( caller(2) )[3], "\n") },
  sub { print('Message: ', $_[0], "\n") },
  sub { print('Exiting: ', ( caller(2) )[3], "\n") }
);

sub debug { $subs[ $_[0] ]->( $_[1] ); }

sub go {
  debug( 0 );
  # ...
  debug( 1, "everything looks good..." );
  do_some_work();
  # ...
  debug( 2 );
}

sub do_some_work {
  debug( 0 );
  # ...
  debug( 1, "having a wonderful time..." );
  # ...
  debug( 2 );
}

go();
Ctrl-D
Entering: main::go
Message: everything looks good...
Entering: main::do_some_work
Message: having a wonderful time...
Exiting: main::do_some_work
Exiting: main::go

Notice how the debug() subroutine is simply a dispatcher for the subroutines
stored in the @subs array? Of course my actual debugger is slightly more
complcated, but thats how it uses code refs.

There are countless other ways to use the feature. Passing subroutines as
arguments to other subroutines comes to mind.

> 2. Any "name" for this kind of coding style ?

I dont know of a name, but I guess I wouldnt call it a coding style. Storing
code in variables is a language feature. When you dont need the feature, you
dont use it. Read "perldoc perlref".

Todd W.





-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to