```{index} single: cast; Peta::XS function ``` ```{index} single: Peta::XS::cast; Perl function ``` # cast Attach a wizard to the variable `$ref` points at. ## Synopsis ```perl use Peta::XS ':magic'; my $x; cast(\$x, $w); # true cast(\$x, $w); # false - same wizard twice is a no-op cast(\$x, $other, 1, 2); # @args reach $other's data callback ``` ## What you get back True when the wizard was attached, false when this wizard was already on the variable (casting twice is a no-op and calls no callbacks). The cast itself fires nothing - the first `get`/`set` comes from the first read/write after it. ## Contract If the wizard has a `data` callback it is called once, here, as `$data_cb->(\$referent, @args)`, and its return value becomes the attachment's private data (see [`getdata`](getdata)). Multiple distinct wizards may be cast on one variable; they fire most recently cast first. Readonly variables can be cast (attaching magic does not write the value - writes still croak before `set` would fire). The attachment lives exactly as long as the variable or until [`dispell`](dispell)ed. ## Examples ```perl ## any scalar works, including aggregate elements my @row = (1, 2, 3); cast(\$row[1], $watch); # watch one array element my %cfg = (mode => 'dev'); cast(\$cfg{mode}, $watch); # watch one hash value ## cast args parameterize the attachment via the data callback my $tagged = wizard( data => sub { my ($ref, $tag) = @_; $tag }, set => sub { warn "[$_[1]] changed\n" }, ); cast(\my $a, $tagged, 'alpha'); cast(\my $b, $tagged, 'beta'); $a = 1; # warns "[alpha] changed" $b = 2; # warns "[beta] changed" ``` ## See also - [`wizard`](wizard) - build the handle and its callbacks. - [`dispell`](dispell) - the inverse operation. - [`getdata`](getdata) - fetch what the data callback returned.