Another issue: Changing one variable instantly changes the value of another variable
#10
(06-17-2022, 02:08 PM)bplus Wrote: IMHO this is how I would handle this function:
Code: (Select All)
' don't share temp$, temp$ is supposed to be temporary!!!
test$ = "C:\Dir1\Dir2\"
Print CleanPath$(test$)

Function CleanPath$ (Path$) ' this is clearly a Function in my opinion!

    ' Remove quotes and trailing backslash from a path

    ' To use this subroutine: Pass the path to this sub, the sub will return the path
    ' without quotes and a trailing backslash in Temp$.

    Dim x As Integer

    ' start by stripping the quotes

    Temp$ = ""

    For x = 1 To Len(Path$)
        If Mid$(Path$, x, 1) <> Chr$(34) Then
            Temp$ = Temp$ + Mid$(Path$, x, 1)
        End If
    Next x

    ' Remove the trailing backslash, if present

    If Right$(Temp$, 1) = "\" Then
        Temp$ = Left$(Temp$, (Len(Temp$) - 1))
    End If
    CleanPath$ = Temp$
End Function


How do you get double quotes in a path or filename? (Just really curious!)

You'd still end up with the same root issue though when you did a return$ = ClearPath(Temp$).   If I was going the way you're mentioning, I'd do it like so:


Code: (Select All)
Function CleanPath$ (Path$) ' this is clearly a Function in my opinion!


    STATIC Temp$ 'Make certain that Temp$ is local to the sub and we don't use the global variable by accident


    ' Remove quotes and trailing backslash from a path

    ' To use this subroutine: Pass the path to this sub, the sub will return the path
    ' without quotes and a trailing backslash in Temp$.

    Dim x As Integer

    ' start by stripping the quotes

    Temp$ = ""

    For x = 1 To Len(Path$)
        If Mid$(Path$, x, 1) <> Chr$(34) Then
            Temp$ = Temp$ + Mid$(Path$, x, 1)
        End If
    Next x

    ' Remove the trailing backslash, if present

    If Right$(Temp$, 1) = "\" Then
        Temp$ = Left$(Temp$, (Len(Temp$) - 1))
    End If
    CleanPath$ = Temp$
End Function

Notice that Temp$ is now a STATIC variable, forced to be localized to the Function itself, and thus can't ever be corrupted via the global variable named Temp$.  There's a reason why QBASIC offered STATIC and local variables, even if most people never bothered to use them.  Wink
Reply


Messages In This Thread
RE: Another issue: Changing one variable instantly changes the value of another variable - by SMcNeill - 06-17-2022, 02:17 PM



Users browsing this thread: 1 Guest(s)