1

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;
}

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Or you could do my $url = $somethingelse; outside the loop and change it if that condition is true.
@Sobrique Why contradict yourself and make the computer do extra work?
Because the computer doesn't deserve to have an easy time of it. It's been naughty and must be punished. But honestly, it depends on scenario - if usually it'll be one state, but occasionally it will be different, setting the 'default state' and switching it on hitting the exception I feel improves code clarity.
4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.