Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Printing a Variable outside of the block

by olus (Curate)
on Apr 15, 2008 at 16:24 UTC ( [id://680559]=note: print w/replies, xml ) Need Help??


in reply to Printing a Variable outside of the block

What block are you referring to? Your code prints correctly all those lines without the '*'. What and where do you want that stuff being printed?

  • Comment on Re: Printing a Variable outside of the block

Replies are listed 'Best First'.
Re^2: Printing a Variable outside of the block
by trenchwar (Beadle) on Apr 15, 2008 at 16:25 UTC
    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";
      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.

      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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://680559]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-25 10:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found