in reply to Re: Printing a Variable outside of the block
in thread Printing a Variable outside of the block

For example, if I wanted to do it like below.
#!/usr/bin/perl use warnings; use strict; my @l; open (FH3, ">lessons.txt"); print FH3 "Perl*Lesson1\n"; print FH3 "Perl*Lesson2\n"; print FH3 "Perl*Lesson3\n"; print FH3 "Java*Lesson1\n"; print FH3 "Java*Lesson2\n"; print FH3 "Java*Lesson3\n"; print FH3 "PHP*Lesson1\n"; print FH3 "PHP*Lesson2\n"; print FH3 "PHP*Lesson3\n"; close (FH3); my $l="lessons.txt"; open FH3, "<", $l or die "$l: $!\n"; @l=<FH3>; for my $line (@l){ chomp $line; my ($part1, $part2) = split /\*/,$line; } print "$part1 $part2\n";

Replies are listed 'Best First'.
Re^3: Printing a Variable outside of the block
by moritz (Cardinal) on Apr 15, 2008 at 16:33 UTC
    You can do that if you declare $part1 and $part2 outside the block:
    my ($part1, $part2); for my $line (@l){ chomp $line; ($part1, $part2) = split /\*/,$line; } print "$part1 $part2\n";

    But of course that prints only one line (the last), because each iteration of the block overrides the variables.

    If you don't like that, use an array and push the values onto the array.

Re^3: Printing a Variable outside of the block
by olus (Curate) on Apr 15, 2008 at 16:48 UTC

    Aside from what moritz said, do you really need to have $part1 and $part2? Since you are parsing an array you'll have to go through the process of running all its values. There are quite a few ways to do that. You can

    use the for loop to build the final string to be printed, and print it outside the block

    @l=<F3>; my $text = ''; for my $line (@l){ chomp $line; my ($part1, $part2) = split /\*/,$line; $text .= "$part1 $part2\n"; } print $text;

    create the single string right from the array values by joining them

    @l=<F3>; my $text = join '', @l; $text =~ s/\*/ /g; print $text;

    use a different kind of block

    @l=<F3>; print map {s/\*/ /;$_;} @l;