on-switch
ErrorsCollection

on-switch

Synthesised documentation from type/IO/CatHandle

From type/IO/CatHandle

See Original text in context

has &.on-switch is rw

One of the attributes that can be set during .new call and changed later by assigning to. By default is not specified. Takes a Callable with .count of 0, 1, 2, or Inf. Gets called every time source handle queue may get exhausted is, which happens once during .new call and then each time a source handle is switched to the next one in the queue, or when the source handle queue may get exhausted method is called manually.

If the .count of &.on-switch is 0, it receives no arguments; if it's 1, it receives the currently active handle, and if it's 2 or Inf, it receives the currently active handle, and the last active handle as positional arguments (in that order). On the very first &.on-switch execution, the "last active handle" argument is Nil. Upon source handle queue exhaustion the "currently active handle" argument is Nil, and all the executions made afterwards have both arguments as Nil.

(my $f1 = 'foo'.IO).spurt: "A\nB\nC";
(my $f2 = 'bar'.IO).spurt: "D\nE";
 
my $line;
my $cat = IO::CatHandle.new: :on-switch{ $line = 1 }$f1$f2;
say "{$cat.path}:{$line++} $_" for $cat.lines;
# OUTPUT: 
# foo:1 A 
# foo:2 B 
# foo:3 C 
# bar:1 D 
# bar:2 E 
my @old-stuff;
sub on-switch ($new$old{
    $new and $new.seek: 1SeekFromBeginning;
    $old and @old-stuff.push: $old.open.slurp: :close;
}
 
(my $f1 = 'foo'.IO).spurt: "A\nB\nC";
(my $f2 = 'bar'.IO).spurt: "D\nE";
my $cat = IO::CatHandle.new: :&on-switch$f1$f2;
$cat.lines.raku.say# OUTPUT: «("", "B", "C", "", "E").Seq␤» 
@old-stuff.raku.say# OUTPUT: «["A\nB\nC", "D\nE"]␤»