in reply to variable has value but then become empty

First, please wrap your code, data and expected output within <code></code> tags.

You should always use strict; and use warnings;. I believe the problem you're having is that you don't define $public_key_type prior to the loop. perl lexicalizes variables, so if you define something within a scope, that variable will not be accessible outside of that scope; this is by design.

You don't show the beginning of the while loop, so I've guessed. Try something like the following (untested):

use strict; use warnings; my $public_key_type; while (my $line = <DATA>){ if ( $line =~ /^Public Key Type:/ ) { $public_key_type = scalar <DATA> for 1; $public_key_type =~ s/^\s+//; $public_key_type =~ s/\s+$//; $public_key_type =~ s/\R//g; } } print "$public_key_type\n";

-stevieb

Replies are listed 'Best First'.
Re^2: variable has value but then become empty
by AnomalousMonk (Archbishop) on Sep 09, 2015 at 16:19 UTC
    perl lexicalizes variables, so if you define something within a scope, that variable will not be accessible outside of that scope ...

    I think this is quite misleading. It doesn't make any distinction between lexical and package variables. The point should be clearly made that an automatically created or "autovivified" variable (which is what  $public_key_type might possibly be; no way to know from the code fragment shown) is a package global and visible (update: and accessible) everywhere. The following example runs with warnings, but of course can only run without strict (and a good thing, too!):

    c:\@Work\Perl\monks>perl -le "use warnings; ;; while (! $xyzzy || $xyzzy < 5) { ++$xyzzy; } print $xyzzy; ;; print for grep m{ xyzzy \z }xms, keys %main::; " 5 xyzzy
    Printing the  %main:: package namespace hash after the code is run shows autovivification of the variable globally.


    Give a man a fish:  <%-{-{-{-<