zachary adams
zachary adams

Reputation: 83

Perl variables scoped within a sub

How would I scope to this variable depending on a conditional of papertype?

I have tried it several ways and I am getting errors and I am befuddled.

sub paperdisplay_getPaperLink {
    my ( $self, $args ) = @_;
    my $paper    = $args->{paper};
    my $linktext = $args->{linktext};
    my $session  = $args->{session};

    my $query    = $self->request;
    my $password = $query->param('password');

    if ( $paper->{Type} eq 'Break' ) {
        my $url = $something;
    } else {
        my $url = $somethingelse;
    }

    my $link = qq(<a title="$linktext" target="other" href="$url">$linktext</a>);

    return $link;
}

Upvotes: 1

Views: 76

Answers (2)

Ron Bergin
Ron Bergin

Reputation: 1068

Use the Conditional Operator to initialize a variable without the need for an if block:

my $url = $paper->{Type} eq 'Break'
    ? $something
    : $somethingelse;

Upvotes: 4

amphetamachine
amphetamachine

Reputation: 30595

You have to declare it in the block you want to use it in. If you declare it inside the if or else block, it'll only exist there. The variable would be destroyed when the block ends.

my $url;
if ($paper->{Type} eq 'Break') {
    $url = $something
} else {
    $url = $somethingelse
}
# $url still exists down here

Upvotes: 6

Related Questions