Reputation: 101
I want to read numbers from a text file. Those can be scalars or arrays.
So either I call
real, dimension(2) :: test
call self%ReadRealToVariable('(2F10.0)',test)
or
real :: test
call self%ReadRealToVariable('(F10.0)',test)
The import function looks like
subroutine ReadRealToVariable(self,Format,VarOut)
implicit none
! Declaring Part
class(FileImporter) :: self
real, dimension(:), intent(out) :: VarOut
character(len=*), intent(in) :: Format
real, dimension(size(VarOut)) :: Value
! Executing Part
call self%ReadValueToVariable(Format,Value)
end subroutine ReadRealToVariable
The problem is now that when I try to import a scalar, I get a dimension mismatch between scalar and rank(1). I understand fully why this problem occurs. The question now is how to handle it:
Is there a way to flexibly allocate a variable to both a scalar or an array?
Or should I simply initialize all scalars as real, dimension(1) :: test
?
Upvotes: 0
Views: 134
Reputation: 78354
In the interests of having an answer to the question that people can see ...
1) No, a single routine won't be able to allocate a scalar if passed a scalar, and an array if passed an array. It is possible to wrap different routines behind a generic interface and make it appear as if a single procedure were behaving as OP wants. That may well be good enough. OP seems to have figured this out, and there are probably several other questions here on SO about generic interfaces so I won't write more on the topic here.
2) One could certainly treat scalars as rank-1 arrays of size 1 for the purposes of writing a routine to read the values from a file. Whether one would want to spread this throughout a codebase I'm not sure. On the other hand, I can see situations where having a rank 1 array of size 1 is useful in the way that arrays of size 0 are useful, such as for dealing with edge cases without complicated conditionals.
Upvotes: 2