Substr function not working with IF statement

I am reading a file with various length strings that i must cut at various start and end positions (left to right). Sometimes the start position is larger than the end position which tells me to cut the string from right to left.

I have the following code. If $start is larger than $end, it will not create the substring. The substr function only works if $end is larger than $start. Not sure why this is happening. If I remove the IF/ELSE statement the substr works fine even if $start is larger than $end. Any help would be appreciated.

 $start = 20;
 $end = 10;
 $len = 5
 $string = "THISISALONGSTRINGTHATWILLNOTSPLICEUNLESSIREMOVETHEIFSTATEMENT";

 if ($start > $end){
   my $slice = substr($string, $end, $len);
 }
 else{
   my $slice = substr($string, $start, $len);
 }

Answers


my $slice;
if ($start > $end){
  $slice = substr($string, $end, $len);
}
else{
  $slice = substr($string, $start, $len);
}

or perhaps

my $slice = ($start > $end) 
  ? substr($string, $end, $len) 
  : substr($string, $start, $len);

The my $slice seems to be wrong, it will go out of scope at the next } which means $slice won't be set after the if/else condition. Put a my $slice; in front of the if and remove the my in the substr statements.

Edit: What mpapec says, he was faster than me.


In modern Perl, most variables are lexically scoped. This means that they will go in and out of definition depending where they're defined. Variables defined inside of a block will no longer be defined once outside of that block. Think of a block as a pair of curly braces. So, your if statement is a block:

if ( ... )  {  # Beginning of a block
    ....
    ....
}              # End of a block

This means any variable defined (via my) in this block will no longer be defined outside of that if statement.

To get around this, define your variable outside of the if statement, and then change the value:

my $slice;          # Variable is defined here
if ( $start > $end ) {
    $slice = substr($string, $end, $len);
}
else {
    $slice = substr($string, $start, $len);
}
say $slice;         # Variable is still set here.

Need Your Help

PHP changes slow to refresh in browser

php macos .bash-profile

Ever since I added a .bash_profile on my Mac to point to a fresher version of PHP in MAMP, I've noticed my PHP changes take a long time to show in the browser localhost. It's absolutely killing me! I

Desire2Learn: Maximum length of ShortTitle parameter in creation of link topic

desire2learn

In the Desire2Learn Valence API, when making a call to the endpoint