package App::InteractivePerlTutorial::Chapter::Smartmatch::GivenWhen;

use 5.014000;
use strict;
use warnings;
our $VERSION = '0.000_001';

use constant TEXT => 'Given-when';

1;
__DATA__

=encoding utf-8

=head1 Given-when

The given-when control structure make the program run a block of code C<when> the argument C<given> satisfies a condition.

=head2 Similarities and Differences with if-elseif-else Structure

the next 2 program sequences will do the same thing: will read the input and

  given( <STDIN> ) {
  when ( 'virus' )  { say 'the whole file is virus' }
  when ( /\Avirs/ ) { say 'the file name starts with a virus' }
  when ( /virus/ )  { say 'the file is corrupt' }
  default           { "this file is clean" }
  }                                             #note that, in this, case $_ will automatically take the value of the argument of given and the argument of when will be $_ ~~ (...)

  my $_ = <STDIN>;
  if ( $_ ~~ 'Fred' )       { say 'the whole file is virus' }
  elsif ( $_ ~~ /\Avirus/ ) { say 'the file name starts with a virus' }
  elsif ( $_ ~~ /virus/ )   { say 'the file is corrupt' }
  else                      { say "this file is clean" }

On the other hand, if we write this way

  given( <STDIN> ) {
  when ( /virus/ ) { say 'the file is corrupt'; continue }
  when ( 'virus' ) { say 'the whole file is virus' }                    #note that if we write C<continue>and in this C<while>,in the case this one is true, the command block conditioned by C<default> will execute anyway since C<default> is equivalent with C<while(1)>;
  default          { "this file is clean" }
  }

=head2 given-when in combination with foreach

This is used in case we want to go through multiple items. It can look like:

  foreach my $file ( @PC ) {
  given( $file) {
  ...
  }
  }

but it can be shortened by writing it without C<given>, like this:

  say 'scanning...';
  my $nr
  foreach ( @PC ) {
  print 'file number $nr:'
  when ( /virus/ ) { say 'this file is corrupt'; continue }
  when ( 'virus' ) { say 'the whole file is virus' }
  default          { "this file is clean" }
  }
  say 'done';


=cut
